我正在使用 jestjs 测试下面的 NodeJS 函数/模块
const fs = require("fs");
const path = require("path");
function read(filename, callback) {
fs.readFile(path.join(__dirname, filename), { encoding: "utf-8" }, callback);
}
module.exports = {
read,
};
第一个测试是:
test("callback data returned is correct", (done) => {
function callback(err, data) {
try {
expect(data).toBe("1");
done();
} catch (err) {
done(err);
}
}
read("./test", callback);
});
并且是成功的(我有一个真正的 test
文件,内容为 1
。
第二个有点棘手。由于我向 read
提供了一个 mockCallback 函数,为什么没有调用回调函数?
const { read } = require("./callback");
describe("callback testing", () => {
test("callback is called", (done) => {
const mockCallback = jest.fn((err, data) => data);
read("./test", mockCallback);
expect(mockCallback).toHaveBeenCalled();
done();
});
});
测试失败,在检查模拟函数时,它似乎没有被调用。
我还尝试添加以下内容来模拟 fs.readFile
,但没有取得多大成功:
const mock = require("mock-fs");
const fs = require("fs");
jest.mock("fs");
beforeEach(() => {
mock({
test: "1",
});
});
我想要一个能够模拟最少依赖方法的解决方案,并解释为什么不运行回调。
答案 0 :(得分:1)
您应该模拟 fs.readFile
方法并在您的测试用例中触发回调。
例如
callback.js
:
const fs = require('fs');
const path = require('path');
function read(filename, callback) {
fs.readFile(path.join(__dirname, filename), { encoding: 'utf-8' }, callback);
}
module.exports = {
read,
};
callback.test.js
:
const { read } = require('./callback');
const fs = require('fs');
describe('callback testing', () => {
test('callback is called', () => {
const mockCallback = jest.fn();
const mockData = 'mock file data';
const mockReadFile = jest.spyOn(fs, 'readFile').mockImplementationOnce((filename, options, callback) => {
callback(null, mockData);
});
read('./test', mockCallback);
expect(mockCallback).toHaveBeenCalled();
expect(mockReadFile).toBeCalledWith(expect.any(String), { encoding: 'utf-8' }, mockCallback);
mockReadFile.mockRestore();
});
});
单元测试结果:
PASS examples/65361608/callback.test.js
callback testing
✓ callback is called (3 ms)
-------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
callback.js | 100 | 100 | 100 | 100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.992 s, estimated 5 s