跨测试文件共享模拟

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)

sli*_*wp2 0

这是一个解决方案,目录结构如下:

\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\n
Run Code Online (Sandbox Code Playgroud)\n\n

someModule.ts:

\n\n
function findById() {\n  return \'real data by id\';\n}\n\nfunction findByName() {\n  return \'real data by name\';\n}\n\nexport { findById, findByName };\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

main.ts使用someModule.ts

\n\n
import { findById } from \'./someModule\';\n\nfunction main() {\n  return findById();\n}\n\nexport { main };\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

other.ts使用someModule.ts

\n\n
import { findByName } from \'./someModule\';\n\nfunction other() {\n  return findByName();\n}\n\nexport { other };\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

sharedMocks.ts, 嘲笑someModule

\n\n
const findById = jest.fn();\n\nexport { findById };\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

main.spec.ts, 使用sharedMocks

\n\n
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\n
Run Code Online (Sandbox Code Playgroud)\n\n

other.spec.ts,不要使用sharedMocks

\n\n
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\n
Run Code Online (Sandbox Code Playgroud)\n