Fre*_*eez 5 javascript unit-testing reactjs jestjs
我想跨测试文件共享模拟实现,但我不想全局模拟该模块。默认情况下我不需要模拟模块,但在某些情况下我想跨文件应用相同的模拟逻辑。
jest.mock('some-module', () => {
//... long mock implementation
})
Run Code Online (Sandbox Code Playgroud)
我没有找到模块化笑话模拟的方法,我已经尝试了以下技术,但不起作用
// sharedMocks.js
export const mockSomeModule = () => {
jest.mock('some-module', () => { /* ... */ })
}
// from other file
import { mockSomeModule } from '../sharedMocks'
mockSomeModule()
Run Code Online (Sandbox Code Playgroud)
或者
// sharedMocks.js
export const someModuleMock = () => {
//... long mock implementation
}
// from other file
import { someModuleMock } from '../sharedMocks'
jest.mock('some-module', someModuleMock)
Run Code Online (Sandbox Code Playgroud)
这是一个解决方案,目录结构如下:
\n\n.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.spec.ts\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.ts\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 other.spec.ts\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 other.ts\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 sharedMocks.ts\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 someModule.ts\nRun Code Online (Sandbox Code Playgroud)\n\nsomeModule.ts:
function findById() {\n return \'real data by id\';\n}\n\nfunction findByName() {\n return \'real data by name\';\n}\n\nexport { findById, findByName };\n\nRun Code Online (Sandbox Code Playgroud)\n\nmain.ts使用someModule.ts:
import { findById } from \'./someModule\';\n\nfunction main() {\n return findById();\n}\n\nexport { main };\n\nRun Code Online (Sandbox Code Playgroud)\n\nother.ts使用someModule.ts:
import { findByName } from \'./someModule\';\n\nfunction other() {\n return findByName();\n}\n\nexport { other };\n\nRun Code Online (Sandbox Code Playgroud)\n\nsharedMocks.ts, 嘲笑someModule:
const findById = jest.fn();\n\nexport { findById };\n\nRun Code Online (Sandbox Code Playgroud)\n\nmain.spec.ts, 使用sharedMocks
import * as someModule from \'./sharedMocks\';\nimport { main } from \'./main\';\n\njest.mock(\'./someModule.ts\', () => someModule);\n\ndescribe(\'test suites A\', () => {\n it(\'t1\', () => {\n someModule.findById.mockReturnValueOnce(\'mocked data\');\n const actualValue = main();\n expect(actualValue).toBe(\'mocked data\');\n });\n});\n\nRun Code Online (Sandbox Code Playgroud)\n\nother.spec.ts,不要使用sharedMocks
import { other } from \'./other\';\n\ndescribe(\'other\', () => {\n it(\'t1\', () => {\n const actualValue = other();\n expect(actualValue).toBe(\'real data by name\');\n });\n});\n\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1284 次 |
| 最近记录: |