跨测试文件共享模拟

问题描述 投票:0回答:1

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

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)
javascript unit-testing reactjs jestjs
1个回答
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');
  });
});

© www.soinside.com 2019 - 2024. All rights reserved.