我模拟了一些nodejs模块(例如,其中一个是
fs
). 我把它们放在一个盒子里
__mocks__
文件夹(同级)
node_modules
fs公司
模块是:
// __mocks__/fs.js
module.exports = {
existsSync: jest.fn()
.mockReturnValueOnce(1)
.mockReturnValueOnce(2)
.mockReturnValueOnce(3)
}
init()
称为(见下文),
existsSync
从值1开始:的第一个值
jest.fn().mockReturnValue()
// init.test.js
const init = require("../init");
const { existsSync } = require("fs");
jest.mock("fs");
describe("initializes script", () => {
afterEach(() => {
// see below!
});
test("it checks for a package.json in current directory", () => {
init();
});
test("it stops script if there's a package.json in dir", () => {
init(); // should be run in clean environment!
});
}
再一次非常简化了init.js文件
const { existsSync } = require("fs");
console.log("value of mocked response : ", existsSync())
existsSync()
第一次和第二次运行后
当我跑进去的时候
afterEach()
:
-
jest.resetModules():
1
,
2
-
1
,
undefined
-
1
,
2
-
existsSync.mockRestore():
1
未定义
有人知道我做错了什么吗?如何清除同一套件中测试之间的模块模拟?如有必要,我很乐意澄清。谢谢!