3

我正在将 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();
        });
});

如果我在测试运行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.
4

1 回答 1

3

问题是您无法预测获得结果需要多长时间。您可以做的是创建在回调中解析的 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.
      }))
    });
于 2017-02-21T07:54:38.050 回答