2017-02-21 63 views
3

我正在使用Jest和JS,并试图围绕X-ray JS库(一个Web抓取工具包)编写测试。以下是测试。这是从2017年2月20日起使用Jest 18.x和最新的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) [email protected]' }) 
     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. 

回答

2

问题是,你不能预测多久才能得到结果。你可以做的是创建回调中的承诺并从你的测试中返回这个承诺

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) [email protected]' 
     }) 
     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. 
     })) 
    }); 
相关问题