Sinon TypeError: Attempted to wrap undefined property getInternationals as function

Viewed 1846

I'm using Cypress to write an integration test. Cypress uses Sinon for stubs and spies so cy.spy = sinon.spy.

I'm trying to spy on a method from an imported module.

I'm importing the module like so: import * as internationals from "../../../src/api/Internationals";

I then try to spy on a method inside api/Internationals like so: cy.spy(internationals, "getInternationals");

Resulting in this error:

TypeError: Attempted to wrap undefined property getInternationals as function

Contents of api/Internationals.js:

import ApiClient from "./ApiClient";

export const getInternationals = ({ search, team, from, till, page = 1, per_page = 10, sort_column, sort_direction }) =>
  ApiClient.get(`/players`, {
    params: {
      search: search ? (search === "#" ? "hek" : search) : null,
      team: team ? team : null,
      from: from ? from : null,
      till: till ? till : null,
      page: page,
      per_page: per_page,
      sort_column: sort_column ? sort_column : null,
      sort_direction: sort_direction ? sort_direction : null
    }
  });

Test contents:

/// <reference types="Cypress" />

import * as internationals from "../../../src/api/Internationals";

describe("Can search for internationals", () => {
  it("Remembers filters after refreshing", () => {
    console.log(internationals);
    cy.spy(internationals, "getInternationals");

    expect(internationals.getInternationals).to.be.called;
  });
});

Console logging internationals shows: enter image description here

Am I missing something?

1 Answers

Tracking through the error in the console, it's clear that Cypress is not handling the export const getInternationals construct correctly, but cannot tell why at a glance.


NOTE: re-basing the import doesn't work, left for continuity of discussion

You can dodge the problem by spying like this in your test

const spyBase = {
  getInternationals: internationals.getInternationals
}
cy.spy(spyBase, "getInternationals");

expect(spyBase.getInternationals).to.be.called;

If you can alter the source code, add a default export to the module

export const getInternationals = ...

export default {
  getInternationals
}

and import it like so

import internationals from "../../../src/api/Internationals";
Related