gpt4 book ai didi

typescript - 如何使用 Jest 和 TypeScript 模拟第三方 nodejs 模块功能?

转载 作者:行者123 更新时间:2023-12-03 13:44:34 27 4
gpt4 key购买 nike

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

最佳答案

这里有几种不同的模拟方式,例如 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()
});

});

使用工厂模拟模块

通过 module factory to 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
});
});

自动模拟模块

创建 a mock for the module .
Jest将自动使用模拟,除非它是核心节点模块(如 fs )在这种情况下 calling jest.mock() is required .

__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;

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
});
});

关于typescript - 如何使用 Jest 和 TypeScript 模拟第三方 nodejs 模块功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52113681/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com