javascript - 跨测试文件共享模拟

标签 javascript unit-testing reactjs jestjs

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

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

我没有找到模块化 Jest 模拟的方法,我已经尝试过以下技术,但不起作用

// 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)

最佳答案

这是一个解决方案,目录结构是这样的:

.
├── 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');
  });
});

关于javascript - 跨测试文件共享模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43292263/

相关文章:

unit-testing - 私有(private)/ protected 方法是否应该进行单元测试?

Javascript:根据当前日期检查格式化的日期值?

javascript - 如何使用 Jest 测试节点列表

javascript - 使用 Bootstrap Tab 循环工作的“下一个-上一个”按钮

c# - 如何测试这个业务逻辑

javascript - 在 React/Redux 中在屏幕上一一显示内容

json - 使用 jsonwebtoken 登录安全

javascript - 如何有条件地为组件设置 onClick 属性,而不必重复嵌套代码行?

javascript - 如何在新标签页中打开 YouTube 嵌入式视频?

javascript - JQuery 在鼠标单击时显示和隐藏 div(动画)