I have a very simple unit test that looks like this:
import ApiWrapper from '../../services/api_wrapper';
jest.unmock('../helper')
describe('Helper', () => {
let Helper;
beforeEach(() => {
Helper = require('../helper').default;
});
it('calls the Api Wrapper', () => {
Helper.help()
expect(ApiWrapper.help).toHaveBeenCalled();
});
});
Where Helper looks like this:
import ApiWrapper from '../services/api_wrapper'
class Helper {
help() {
ApiWrapper.help()
}
}
export default new Helper();
And ApiWrapper looks like this:
class ApiWrapper {
static help () {
console.log('help!')
}
}
export default ApiWrapper;
ApiWrapper.help() gets mocked by Jest so 'help!' never gets printed, yet the expectation in the test fails. This still fails if we rewrite ApiWrapper to just be a plain Javascript object like such:
export default {
help: () => { console.log('help!'); }
}
It works, however, if we change the imports in the spec (so ApiWrapper is imported in the beforeEach), and rewrite ApiWrapper to be a Singleton class, like so:
class ApiWrapper {
help() {
console.log('help!');
}
}();
export default new ApiWrapper();
What is it about Jest's mocking behavior that makes this happen?
Aucun commentaire:
Enregistrer un commentaire