'Why does jest mock test give me undefined?
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 !!
Solution 1:[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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
