[英]Unit testing async function with callback
Trying to write unit tests for reading a json file with the readFile function however I get the error: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout. 尝试编写使用readFile函数读取json文件的单元测试,但出现错误:超时-在jest.setTimeout指定的5000ms超时内未调用异步回调。 I must be doing something wrong when mocking the json file.
模拟json文件时,我一定做错了。
The function: 功能:
function jsonReader(filePath, cb) {
fs.readFile(filePath, (err, fileData) => {
if (err) {
return cb && cb(err);
}
try {
const object = JSON.parse(fileData);
return object;
} catch (err) {
return cb && cb(err);
}
});
}
module.exports = jsonReader;
Then the testfile: 然后是测试文件:
const jsonReader = require('.././ReadJson');
jest.mock('fs', () => {
const MOCK_FILE_INFO = { 'test.json': JSON.stringify({ name: 'myname' }) };
return {
readFile: (fpath, opts) => {
if (fpath in MOCK_FILE_INFO) {
return MOCK_FILE_INFO[fpath];
}
}
};
});
test('Test file', (done) => {
function callback(data) {
expect(data.name).toBe('myname');
done();
}
jsonReader('test.json', callback);
});
I tried to change the timeout but if I put it higher the execution also takes longer and it's still giving the same error. 我试图更改超时时间,但是如果我将超时时间设置得更高一些,则执行也将花费更长的时间,并且仍然出现相同的错误。
You're trying to use your functions synchronously? 您正在尝试同步使用功能吗?
jest.mock('fs', () => {
const MOCK_FILE_INFO = { 'test.json': JSON.stringify({ name: 'myname' }) };
return {
readFile: (fpath, callback) => {
if (fpath in MOCK_FILE_INFO) {
callback(null, MOCK_FILE_INFO[fpath]);
}
}
};
});
function jsonReader(filePath, cb) {
fs.readFile(filePath, (err, fileData) => {
if (err) {
return cb && cb(err);
}
try {
const object = JSON.parse(fileData);
cb(object);
} catch (err) {
return cb && cb(err);
}
});
}
module.exports = jsonReader;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.