跨测试文件共享模拟

时间:2017-04-08 09:17:21

标签: javascript unit-testing reactjs jestjs

我想在测试文件中共享一个模拟实现,但我不想全局模拟该模块。我不需要默认模拟模块,但在某些情况下我想在文件中应用相同的模拟逻辑。

jest.mock('some-module', () => {
   //... long mock implementation
})

我没有找到模块化模拟嘲讽的方法,我已经尝试了以下技巧,哪些不起作用

// sharedMocks.js
export const mockSomeModule = () => {
    jest.mock('some-module', () => { /* ... */ })
}

// from other file
import { mockSomeModule } from '../sharedMocks'
mockSomeModule()

// sharedMocks.js
export const someModuleMock = () => {
    //... long mock implementation
}

// from other file
import { someModuleMock } from '../sharedMocks'
jest.mock('some-module', someModuleMock)

1 个答案:

答案 0 :(得分:0)

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

.
├── main.spec.ts
├── main.ts
├── other.spec.ts
├── other.ts
├── sharedMocks.ts
└── someModule.ts

someModule.ts

function findById() {
  return 'real data by id';
}

function findByName() {
  return 'real data by name';
}

export { findById, findByName };

main.ts使用someModule.ts

import { findById } from './someModule';

function main() {
  return findById();
}

export { main };

other.ts使用someModule.ts

import { findByName } from './someModule';

function other() {
  return findByName();
}

export { other };

sharedMocks.ts,模拟someModule

const findById = jest.fn();

export { findById };

main.spec.ts,使用sharedMocks

import * as someModule from './sharedMocks';
import { main } from './main';

jest.mock('./someModule.ts', () => someModule);

describe('test suites A', () => {
  it('t1', () => {
    someModule.findById.mockReturnValueOnce('mocked data');
    const actualValue = main();
    expect(actualValue).toBe('mocked data');
  });
});

other.spec.ts,请勿使用sharedMocks

import { other } from './other';

describe('other', () => {
  it('t1', () => {
    const actualValue = other();
    expect(actualValue).toBe('real data by name');
  });
});