1

I am new to learning jest mocks. I am trying out a very simple test. I have a folder greeter. This folder has a file 'greeter.js' and a subfolder called 'test'. The 'test' folder has a test called greeter.test.js. Here is the code

greeter.js

function greet(fname, lname) {
    return "hello " + greetWithName(fname, lname)
}

export function greetWithName(fname, lname) {
    return fname + " : " + lname
}
 
export default greet

and the test is:

import greet, {greetWithName} from '../greeter'

jest.mock("../greeter")

describe('checks greeter module', () => {
    it ('greet', () => {
        greetWithName.mockReturnValue("hero");
        expect(greet("a", "b")).toBe("hello hero") // fails
    })
})

Curios why expect(greet("a", "b")).toBe("hello hero") fails, it is undefined. Not sure why ?

When checked for expect(greetWithName("a", "b")).toBe("hero") : passes !!

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • Duplicated https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest – Lin Du Apr 18 '22 at 06:14

1 Answers1

1

jest.mock('../greeter') is mocking the whole greeter.js module, and since you don't provide a mockReturnValue for greet it's returning undefined.

By default, jest.mock mocks all exports from a module to return undefined unless you provide mock return values. You're mocking greetWithName to return a value, but greet is also being mocked.

To get the behavior you want, you could either move greet into a separate module (which you don't mock), or use jest.requireActual to mock certain functions in a module but not others.

helloitsjoe
  • 6,264
  • 3
  • 19
  • 32