jeudi 28 janvier 2021

How to spy on named function?

I am trying to spy on a named function, exported from the same file from the function I am trying to test. I want to test that function has been called. I want to avoid mocking it completely so that I can have another test for it.

I have utils file like so where I declare my 2 methods

// utils.js
export const myFunction = () => {
  return myOtherFunction()
};

export const myOtherFunction = () => {
  return true
}

I am then testing them here like so:

//utils.test.js
import * as utils from "./utils"

describe("myFunction", () => {
  it("should call myOtherFunction", () => {
    jest.spyOn(utils, "myOtherFunction").mockReturnValue(true)
    const result = utils.myFunction()
    expect(utils.myOtherFunction).toHaveBeenCalledTimes(1)
    expect(result).toEqual(true)
  })
})

It fails because of the following:

Expected number of calls: 1
Received number of calls: 0

Aucun commentaire:

Enregistrer un commentaire