如果在异步函数中调用“expect”,则Jest异步测试会超时。有时工作。 “在指定的超时时间内未调用异步回调”

时间:2017-02-21 05:01:22

标签: javascript jasmine jestjs jasmine2.0 x-ray

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

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();
        });
});

如果我删除expect().toEqual测试运行上方回调内的done()来电话:

 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.

1 个答案:

答案 0 :(得分:3)

问题是您无法预测获得结果所需的时间。你可以做的是创建在回调中解决的promises并从你的测试中返回这个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.
      }))
    });