为调用 fs 写文件的编辑函数编写单元测试



我正在编写一个函数来读取,写入和编辑本地存储的json文件。已经编写了函数。在为 Edit 函数编写单元测试时遇到问题。

我正在使用Jest来编写测试用例。在读写功能方面取得了成功。但是编辑函数有问题,它将更改值的确切位置作为参数,然后调用writeFile

function jsonEditor(path, version, prot, index, layer, field, value) {
// Read json
jsonReader(path).then((response) => {
const fileData = response;
fileData[version][prot].connections[index][layer][field] = value;
//call the WriteFile function
writeFile(path, JSON.stringify(fileData, null, 2), (err) => {
if (err) throw err;
});
});
}

无法理解如何在这里使用模拟。

下面是一个单元测试解决方案:

index.ts

import fs from 'fs';
export const jsonReader = async (path): Promise<any> => {
return { v1: { a: { connections: [{ someLayer: { someField: 'real value' } }] } } };
};
export function jsonEditor(path, version, prot, index, layer, field, value) {
// Read json
return jsonReader(path).then(response => {
const fileData = response;
fileData[version][prot].connections[index][layer][field] = value;
// call the WriteFile function
fs.writeFile(path, JSON.stringify(fileData, null, 2), err => {
if (err) throw err;
console.log('write file successfully');
});
});
}

index.spec.ts

import fs from 'fs';
import * as jsonUtils from './';
describe('jsonUtils', () => {
afterEach(() => {
jest.restoreAllMocks();
});
describe('#jsonEidtor', () => {
test('should read json and write file correctly', async () => {
let callback;
jest.spyOn(fs, 'writeFile').mockImplementation((path, data, cb) => {
callback = cb;
});
const logSpy = jest.spyOn(console, 'log');
const mResponse = { v2: { b: { connections: [{ someLayer: { someField: '' } }] } } };
jest.spyOn(jsonUtils, 'jsonReader').mockResolvedValueOnce(mResponse);
await jsonUtils.jsonEditor('somePath', 'v2', 'b', 0, 'someLayer', 'someField', 'fake value');
expect(fs.writeFile).toBeCalledWith(
'somePath',
JSON.stringify({ v2: { b: { connections: [{ someLayer: { someField: 'fake value' } }] } } }, null, 2),
callback
);
callback();
expect(logSpy).toBeCalledWith('write file successfully');
});
test('should throw error when write file error', async () => {
let callback;
jest.spyOn(fs, 'writeFile').mockImplementation((path, data, cb) => {
callback = cb;
});
const logSpy = jest.spyOn(console, 'log');
const mResponse = { v2: { b: { connections: [{ someLayer: { someField: '' } }] } } };
jest.spyOn(jsonUtils, 'jsonReader').mockResolvedValueOnce(mResponse);
await jsonUtils.jsonEditor('somePath', 'v2', 'b', 0, 'someLayer', 'someField', 'fake value');
expect(fs.writeFile).toBeCalledWith(
'somePath',
JSON.stringify({ v2: { b: { connections: [{ someLayer: { someField: 'fake value' } }] } } }, null, 2),
callback
);
const err = new Error('write file error');
expect(() => callback(err)).toThrowError(err);
expect(logSpy).not.toBeCalled();
});
});
describe('#jsonReader', () => {
test('should return response', async () => {
const actualValue = await jsonUtils.jsonReader('somePath');
expect(actualValue).toEqual({ v1: { a: { connections: [{ someLayer: { someField: 'real value' } }] } } });
});
});
});

100% 覆盖率的单元测试结果:

PASS  src/stackoverflow/57671298/index.spec.ts (6.941s)
jsonUtils
#jsonEidtor
✓ should read json and write file correctly (11ms)
✓ should throw error when write file error (2ms)
#jsonReader
✓ should return response (2ms)
console.log node_modules/jest-mock/build/index.js:860
write file successfully
----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        8.178s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57671298

最新更新