如何使用带有 TypeScript 的 jest 来模拟第三方 nodejs 模块函数?

nic*_*y88 8 mocking npm typescript jestjs

我正在尝试fs.readFileSync()使用 jest模拟第三方节点模块中的函数,特别是该函数。有很多例子,但我还没有找到一个使用 TypeScript 的例子。我在github 上有一个简单的,希望最小的例子。对于熟悉 jest 的人来说,这可能是一个简单的问题。

Bri*_*ams 16

这里有几种不同的模拟方式,例如fs.readFileSync()

模拟功能

模拟一个函数jest.spyOn()与如下函数结合使用mockImplementation()

import { returnNameInJsonFile } from './index';
import * as fs from 'fs';

describe('index', () => {

  it('returnNameInJsonFile', () => {
    const mock = jest.spyOn(fs, 'readFileSync');  // spy on fs.readFileSync()
    mock.mockImplementation(() => JSON.stringify({ name: 'myname' }));  // replace the implementation

    const name: string = returnNameInJsonFile('test.json');
    expect(name).toBe('myname');

    mock.mockRestore();  // restore fs.readFileSync()
  });

});
Run Code Online (Sandbox Code Playgroud)

使用工厂模拟模块

模块工厂jest.mock()传递

import { returnNameInJsonFile } from './index';

jest.mock('fs', () => {
  const MOCK_FILE_INFO = { 'test.json': JSON.stringify({ name: 'myname' }) };
  return {
    readFileSync: (fpath, opts) => {
      if (fpath in MOCK_FILE_INFO) {
        return MOCK_FILE_INFO[fpath]
      }
      throw 'unexpected fpath'
    }
  }
});

describe('index', () => {
  it('returnNameInJsonFile', () => {
    const name: string = returnNameInJsonFile('test.json');
    expect(name).toBe('myname'); // 1.0.0 is installed and 2.0.0 is available
  });
});
Run Code Online (Sandbox Code Playgroud)

自动模拟模块

为模块创建一个模拟

Jest将自动使用模拟,除非它是核心 Node 模块(如fs),在这种情况下需要调用jest.mock()

__mocks__/fs.ts:

const fs = jest.genMockFromModule('fs');

let mockFiles: object = {};

function __setMockFiles (newMockFiles: object) {
  mockFiles = newMockFiles;
}

function readFileSync(filePath: string) {
  return mockFiles[filePath] || '';
}

// If anyone knows how to avoid the type assertion feel free to edit this answer
(fs as any).__setMockFiles = __setMockFiles;
(fs as any).readFileSync = readFileSync;

module.exports = fs;
Run Code Online (Sandbox Code Playgroud)

index.test.ts:

import { returnNameInJsonFile } from './index';

jest.mock('fs');  // Required since fs is a core Node module

describe('index', () => {

  const MOCK_FILE_INFO = { 'test.json': JSON.stringify({ name: 'myname' }) };

  beforeEach(() => {
    require('fs').__setMockFiles(MOCK_FILE_INFO);
  });

  it('returnNameInJsonFile', () => {
    const name: string = returnNameInJsonFile('test.json');
    expect(name).toBe('myname'); // 1.0.0 is installed and 2.0.0 is available
  });
});
Run Code Online (Sandbox Code Playgroud)