Jest can#39;t test an awaited promise, it times out instead(笑话不能测试期待的承诺,相反,它会超时。)
问题描述
我从只运行axios get切换到返回承诺,现在我的Jest测试失败了:
下载‘resource ce.js’中的压缩文件:
async function downloadMtgJsonZip() {
const path = Path.resolve(__dirname, 'resources', fileName);
const writer = Fs.createWriteStream(path);
console.info('...connecting...');
const { data, headers } = await axios({
url,
method: 'GET',
responseType: 'stream',
});
return new Promise((resolve, reject) => {
let error = null;
const totalLength = headers['content-length'];
const progressBar = getProgressBar(totalLength);
console.info('...starting download...');
data.on('data', (chunk) => progressBar.tick(chunk.length));
data.pipe(writer);
writer.on('error', (err) => {
error = err;
writer.close();
reject(err);
});
writer.on('close', () => {
const now = new Date();
console.info(`Completed in ${(now.getTime() - progressBar.start) / 1000} seconds`);
if (!error) resolve(true);
// no need to call the reject here, as it will have been called in the
// 'error' stream;
});
});
}
"resource ce.spec.js"中的以下测试现在均未通过:
it('fetches successfully data from an URL', async () => {
const onFn = jest.fn();
const data = { status: 200, data: { pipe: () => 'data', on: onFn }, headers: { 'content-length': 100 } };
const writerOnFn = jest.fn();
axios.mockImplementationOnce(() => data);
fs.createWriteStream.mockImplementationOnce(() => ({ on: writerOnFn }));
await downloadMtgJsonZip();
expect(onFn).toHaveBeenCalledWith('data', expect.any(Function));
expect(axios).toHaveBeenCalledWith(
expect.objectContaining({ url: 'https://mtgjson.com/api/v5/AllPrintings.json.zip' }),
);
expect(axios).toHaveBeenCalledWith(
expect.objectContaining({ responseType: 'stream' }),
);
});
it('ticks up the progress bar', async () => {
const tickFn = jest.fn();
const dataOnFn = jest.fn((name, func) => func(['chunk']));
const data = { status: 200, data: { pipe: () => 'data', on: dataOnFn }, headers: { 'content-length': 1 } };
const writerOnFn = jest.fn();
ProgressBar.mockImplementationOnce(() => ({ tick: tickFn }));
axios.mockImplementationOnce(() => data);
fs.createWriteStream.mockImplementationOnce(() => ({ on: writerOnFn }));
await downloadMtgJsonZip();
expect(ProgressBar).toHaveBeenCalledWith(
expect.stringContaining('downloading'),
expect.objectContaining({
total: 1,
}),
);
expect(tickFn).toHaveBeenCalledWith(1);
});
});
值得注意的是,VSCode告诉我,对于‘resource ce.js’‘this expression is not call’中的axios
,Nothing没有mockImplementationOnce
(它‘在类型.上不存在’)。
以前我的downloadMtgJsonZip
看起来是这样的:
async function downloadMtgJsonZip() {
const path = Path.resolve(__dirname, 'resources', 'AllPrintings.json.zip');
const writer = Fs.createWriteStream(path);
console.info('...connecting...');
const { data, headers } = await axios({
url,
method: 'GET',
responseType: 'stream',
});
const totalLength = headers['content-length'];
const progressBar = getProgressBar(totalLength);
const timer = setInterval(() => {
if (progressBar.complete) {
const now = new Date();
console.info(`Completed in ${(now.getTime() - progressBar.start) / 1000} seconds`);
clearInterval(timer);
}
}, 100);
console.info('...starting download...');
data.on('data', (chunk) => progressBar.tick(chunk.length));
data.pipe(writer);
}
测试中唯一不同的是createWriteStream的mock更简单(它显示为fs.createWriteStream.mockImplementationOnce(() => 'fs');
)
我已尝试添加:
afterEach(() => {
jest.clearAllMocks();
jest.resetAllMocks();
});
我已尝试添加writerOnFn('close');
以尝试触发writer.on('close', ...)
。
但我直到收到此错误:
:timeout-未在jest.setTimeout.Timeout指定的5000毫秒超时内调用异步回调-未在jest.setTimeout指定的5000毫秒超时内调用异步回调。错误:
我找不出丢失了什么,无法进行要"调用"的异步调用。last time I had this issue模仿createWriteStream
解决了我的问题,但我看不到其他东西可以模仿?
如何使这些测试再次通过?
推荐答案
如何在测试代码中调用使用writer.on(event, handler)
附加的事件处理程序?writerOnFn
模拟不需要调用传入的处理程序函数吗?如果未调用这些函数,则resolve(true)
永远不会被调用,因此对测试内部await downloadMtgJsonZip();
的调用永远不会解析。
我认为您需要这样的东西
const writerOnFn = jest.fn((e, cb) => if (e === 'close') cb())
当然,您可能想要充实它以区分"error"和"Close"事件,或者如果您有关于"error"条件的测试,请确保更改它。
这篇关于笑话不能测试期待的承诺,相反,它会超时。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:笑话不能测试期待的承诺,相反,它会超时。
基础教程推荐
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在for循环中使用setTimeout 2022-01-01