简体   繁体   中英

Share mocks across test files

I want to share a mock implementation across tests files, but I don't want to mock globally the module. I don't need to mock the module by default, but in some cases I want to apply the same mocking logic across files.

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

I didn't find a way to modularize jest mocks, I already tried the following techniques, wich doesn't work

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

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

or

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

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

Here is a solution, the directory structure like this:

.
├── 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 use someModule.ts :

import { findById } from './someModule';

function main() {
  return findById();
}

export { main };

other.ts use someModule.ts :

import { findByName } from './someModule';

function other() {
  return findByName();
}

export { other };

sharedMocks.ts , mock someModule :

const findById = jest.fn();

export { findById };

main.spec.ts , use 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 , don't use sharedMocks

import { other } from './other';

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM