Reputation: 67
I have an issue with testing a pretty simple of javascript code using jest. So I post the code:
Foo.js
export class Foo {
constructor() {
}
someFn() {
this.internalFn();
}
internalFn() {
}
}
Foo.spec.js
jest.mock('../src/foo');
import {Foo} from '../src/foo';
describe('Foo', () => {
it ('test foo', () => {
const foo = new Foo();
foo.someFn();
expect(foo.someFn.mock.calls.length).toBe(1);
expect(foo.internalFn.mock.calls.length).toBe(1); // why received 0 ???
})
})
Why second expect fail? foo.internalFn is called from foo.someFn.
Upvotes: 1
Views: 107
Reputation: 116
A mock function will actually not do anything (except for counting how often it was called, etc.)
That's why your internalFn()
will bever be called, when you mock the function someFn()
.
// EDIT: Just some clarifications
When you unit test your software you want to test it modular and isolated. Functions should be able to work on their own even when they're called internally by other functions.
When you want to test the function someFn()
you have to mock internalFn()
, because you want to check if internalFn()
was actually called by calling someFn()
.
If you want to to test anything else that will call someFn()
you have to mock that instead.
Upvotes: 1