gpt4 book ai didi

javascript - 如果在异步函数中调用 "expect",Jest 异步测试会超时。有时工作。 "Async callback was not invoked within timeout specified"

转载 作者:行者123 更新时间:2023-11-29 10:32:44 24 4
gpt4 key购买 nike

我正在将 Jest 与 JS 结合使用,并尝试围绕 X-ray JS 库(一个网络抓取工具包)编写测试。下面是测试。这是使用 Jest 18.x 和截至 2017 年 2 月 20 日的最新 x 射线 js。

const htmlResponse = require('../__mocks__/html_response'); // just contains {listingsPage: '<html>....</html>';}

describe('scraper', () => {
it("should get David Nichols' latest study from valid HTML", (done) => {
var listingsHtml = htmlResponse.listingsPage;
const Xray = require('x-ray');
const x = Xray();
expect(x).not.toEqual(null);
var parseHtml = x('#Repo tbody tr', { link: 'td:nth-child(1) a@href' })
parseHtml(listingsHtml, (err, result) => {
console.log(Object.keys(result));
expect(result.link).toEqual('le test'); // commenting this out causes test to pass.
done();
});
});

如果我在 done() 上方的回调中删除 expect().toEqual 调用,测试将运行:

 PASS  src/__tests__/scraper-test.js

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.315s, estimated 6s
Ran all test suites related to changed files.

按原样处理该行,它会超时。 result 是一个简单的对象 {link: 'string'} 测试没有进行网络调用。我尝试将超时值更新为 30 秒,但没有成功。

 FAIL  src/__tests__/scraper-test.js (5.787s)

● scraper › should get David Nichols' latest study from valid HTML

Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

at Timeout.callback [as _onTimeout] (node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/browser/Window.js:480:19)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)

Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 6.641s
Ran all test suites related to changed files.

最佳答案

问题是您无法预测获得结果需要多长时间。您可以做的是创建在回调中解决的 promise ,并从您的测试中返回此 promise

    const htmlResponse = require('../__mocks__/html_response'); // just contains {listingsPage: '<html>....</html>';}
describe('scraper', () = > {
it("should get David Nichols' latest study from valid HTML", (done) = > {
const Xray = require('x-ray');
const x = Xray();
expect(x)
.not.toEqual(null);
var parseHtml = x('#Repo tbody tr', {
link: 'td:nth-child(1) a@href'
})
return new Promise((resolve) = > {
var listingsHtml = htmlResponse.listingsPage;
parseHtml(listingsHtml, (err, result) = > {
resolve(result);
});
})
.then((result = > {
expect(result.link)
.toEqual('le test'); // commenting this out causes test to pass.
}))
});

关于javascript - 如果在异步函数中调用 "expect",Jest 异步测试会超时。有时工作。 "Async callback was not invoked within timeout specified",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42359076/

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