简体   繁体   中英

How to spy/mock minimatch with jest

I am aware of how to mock/spy an ES6 import with jest , but this one gets around my head:

my-module.ts

import minimatch from 'minimatch';

export function foo(pattern: string, str: string): boolean {
  return minimatch(pattern, str);
}

test.ts :

describe('minimatch', () => {
  it('should call minimatch', () => {
    const mock = jest.fn().mockReturnValue(true);
    jest.mock('minimatch', mock);

    foo('*', 'hello');

    expect(mock).toHaveBeenCalled();
  });
});

I've also tried mocking in different way:

import * as minimatch from 'minimatch';
// ...
const mock = jest.fn().mockReturnValue(true);
(minimatch as any).default = mock;

Or even

import {mockModule} from '../../../../../../test/ts/utils/jest-utils';
// ...
const mock = jest.fn().mockReturnValue(true);
const originalModule = jest.requireActual('minimatch');
jest.mock('minimatch', () => Object.assign({}, originalModule, mockModule));

My test fails with all of the above ways to mock.

You can't use jest.mock() inside test case functional scope. You should use it in the module scope.

Eg my-module.ts :

import minimatch from 'minimatch';

export function foo(pattern: string, str: string): boolean {
  return minimatch(pattern, str);
}

my-module.test.ts :

import { foo } from './my-module';
import minimatch from 'minimatch';

jest.mock('minimatch', () => jest.fn());

describe('minimatch', () => {
  it('should call minimatch', () => {
    foo('*', 'hello');
    expect(minimatch).toHaveBeenCalled();
  });
});

Unit test results with 100% coverage:

 PASS  stackoverflow/60350522/my-module.test.ts
  minimatch
    ✓ should call minimatch (6ms)

--------------|---------|----------|---------|---------|-------------------
File          | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------|---------|----------|---------|---------|-------------------
All files     |     100 |      100 |     100 |     100 |                   
 my-module.ts |     100 |      100 |     100 |     100 |                   
--------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.304s, estimated 6s

If you want to mock module inside test case, you should use jest.doMock(moduleName, factory, options) .

Eg

my-module.test.ts :

describe('minimatch', () => {
  it('should call minimatch', () => {
    jest.doMock('minimatch', () => jest.fn());
    const { foo } = require('./my-module');
    const minimatch = require('minimatch');
    foo('*', 'hello');
    expect(minimatch).toHaveBeenCalled();
  });
});

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