我是 Jest 新手,只想对使用第三方节点模块的简单函数实现单元测试。
要测试的函数(假设它存在于 utilFolder.js 中):
import moduleName from 'third_party_module'
const util = {
simple_function() {
const name = moduleName.func1();
}
}
export default util;
测试文件:
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();
});
});
错误:
Expected mock function to have been called, but it was not called.
有什么帮助吗?
最佳答案
使用 jest.mock
模拟模块。这是工作示例:
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();
});
});
单元测试结果:
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
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54729837
关于javascript - 如何正确模拟节点模块以进行 Jest 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54729837/