添加 setupFilesAfterEnv 后模拟函数在 .test 文件中不起作用
mock functions don't work in .test files after adding setupFilesAfterEnv
在 jest.config.js 添加 setupFilesAfterEnv 之后:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
setupFilesAfterEnv: ["./test/setupAfterEnv.ts"]
}
模拟函数在 .test.ts
文件中不再起作用,但在写入 setupFilesAfterEnv 的文件中起作用,如 ./test/setupAfterEnv.ts
模拟函数示例(.test.ts
文件和setupAfterEnv.ts
在同一目录):
jest.mock("../src/service/sendEmail.ts", () => ({
send: () => {
return "MOCK sendEmail sent"
}
}));
我没有收到任何错误,另一个应该被模拟的函数 运行s。当我在 mock 函数中写错路径时,我得到错误 can't find module
。所以看起来它找到了应该模拟的函数,但没有 运行 模拟函数和 运行 另一个函数
如果我在 jest.config.js
中评论 setupFilesAfterEnv 配置,它会再次运行。
文档状态
Warning: Importing a module in a setup file
(as specified by setupTestFrameworkScriptFile)
will prevent mocking for the module in question,
as well as all the modules that it imports.
如果您的 ./test/setupAfterEnv.ts 中有任何 imports/requires,它们可能导入了其他文件,并且在该过程中导入的任何链将无法模拟('../一些模块');在测试中。
我不确定为什么会有这个限制;如果您在 setupAfterEnv.ts 文件本身中调用 mock('../somemodule') ,它将在稍后的测试中被模拟。但我认为这很糟糕,因为只有一些测试可能想要模拟某些模块,而其他人则希望它们不会被模拟。可惜。就我而言,我想导入一个 typeorm 库并连接到数据库。但是创建此连接的 class 导入我们所有的实体,所有实体 classes 导入其他 classes 导入其他 classes 等等......所以什么都没有可笑的。由于此限制,根本无法使用。
在 jest.config.js 添加 setupFilesAfterEnv 之后:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
setupFilesAfterEnv: ["./test/setupAfterEnv.ts"]
}
模拟函数在 .test.ts
文件中不再起作用,但在写入 setupFilesAfterEnv 的文件中起作用,如 ./test/setupAfterEnv.ts
模拟函数示例(.test.ts
文件和setupAfterEnv.ts
在同一目录):
jest.mock("../src/service/sendEmail.ts", () => ({
send: () => {
return "MOCK sendEmail sent"
}
}));
我没有收到任何错误,另一个应该被模拟的函数 运行s。当我在 mock 函数中写错路径时,我得到错误
can't find module
。所以看起来它找到了应该模拟的函数,但没有 运行 模拟函数和 运行 另一个函数如果我在
jest.config.js
中评论 setupFilesAfterEnv 配置,它会再次运行。
文档状态
Warning: Importing a module in a setup file (as specified by setupTestFrameworkScriptFile) will prevent mocking for the module in question, as well as all the modules that it imports.
如果您的 ./test/setupAfterEnv.ts 中有任何 imports/requires,它们可能导入了其他文件,并且在该过程中导入的任何链将无法模拟('../一些模块');在测试中。
我不确定为什么会有这个限制;如果您在 setupAfterEnv.ts 文件本身中调用 mock('../somemodule') ,它将在稍后的测试中被模拟。但我认为这很糟糕,因为只有一些测试可能想要模拟某些模块,而其他人则希望它们不会被模拟。可惜。就我而言,我想导入一个 typeorm 库并连接到数据库。但是创建此连接的 class 导入我们所有的实体,所有实体 classes 导入其他 classes 导入其他 classes 等等......所以什么都没有可笑的。由于此限制,根本无法使用。