我模拟了一些 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())
当我在 afterEach()
中运行时,在第一次和第二次运行 init()
后,我分别得到以下 existsSync()
结果:
- jest.resetModules() :
1
、2
- existsSync.mockReset():
1
,未定义
- existsSync.mockClear():
1
,2
- existsSync.mockRestore():
1
,未定义
有人知道我做错了什么吗?如何清除同一套件中测试之间的模块模拟?如果有必要,我很乐意澄清。谢谢!
最佳答案
重置模块并在每次测试时再次需要它们:
describe("initializes script", () => {
afterEach(() => {
jest.resetModules()
});
beforeEach(() => {
jest.mock("fs");
})
test("it checks for a package.json in current directory", () => {
const init = require("../init");
init();
});
test("it stops script if there's a package.json in dir", () => {
const init = require("../init");
init();
});
}
关于javascript - 如何在 Jest 中的同一测试套件中的测试之间清除模块模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52561147/