Reputation: 20222
In my unit test suite, I have the following mock:
beforeEach(() => {
NativeModules.MyModule = {
myMethod: jest.fn()
};
})
And this unit test that uses it:
it('has some functionality', () => {
console.log(JSON.stringify(NativeModules.MyModule.myMethod));
expect(NativeModules.MyModule.myMethod).toHaveBeenCalledTimes(1);
});
The console.log
function prints undefined
but the test passes.
However, if I add this line:
expect(undefined).toHaveBeenCalledTimes(1);
The test will fail with this message:
expect(jest.fn())[.not].toHaveBeenCalledTimes()
jest.fn() value must be a mock function or spy.
Received: undefined
So how can the unit test pass if NativeModules.MyModule.myMethod
is undefined
?
Upvotes: 1
Views: 436
Reputation: 1173
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined).
If you log the mocked function directly (console.log(NativeModules.MyModule.myMethod
) instead of logging
console.log(JSON.stringify(NativeModules.MyModule.myMethod))
you should see the output you expect.
For example:
console.log(() => {})
console.log(JSON.stringify(() => {}))
Upvotes: 2