Reputation: 41
I'm new to jest and just want to implement a unit test for a simple function that uses a third party node module.
function to test (say it lives in utilFolder.js):
import moduleName from 'third_party_module'
const util = {
simple_function() {
const name = moduleName.func1();
}
}
export default util;
test file:
import util from "utilFolder";
import moduleName from 'third_party_module';
jest.mock("third_party_module", () => ({
func1: jest.fn()
}));
describe("was mocked functions called", () {
test("was mocked functions called??", () => {
util.simple_function();
expect(moduleName.func1).toHaveBeenCalled();
});
});
Error:
Expected mock function to have been called, but it was not called.
Any help please?
Upvotes: 4
Views: 1219
Reputation: 102257
Use jest.mock
mock the module. Here is the working example:
util.js
:
import moduleName from './third_party_module';
const util = {
simple_function() {
const name = moduleName.func1();
}
};
export default util;
third_party_module.js
:
export default {
func1() {}
};
util.spec.js
:
import util from './util';
import moduleName from './third_party_module';
jest.mock('./third_party_module', () => ({
func1: jest.fn()
}));
describe('was mocked functions called', () => {
test('was mocked functions called??', () => {
util.simple_function();
expect(moduleName.func1).toHaveBeenCalled();
});
});
Unit test result:
PASS src/stackoverflow/54729837/util.spec.js (8.414s)
was mocked functions called
✓ was mocked functions called?? (4ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.742s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54729837
Upvotes: 1