【问题标题】:Mocha test error when testing code with jquery promise使用 jquery promise 测试代码时出现 Mocha 测试错误
【发布时间】:2017-04-27 17:12:30
【问题描述】:

我正在尝试测试以下代码。基本上服务器拒绝这个请求,因为某些参数没有按照 api 规范的要求发送。 Api.createRecord 在后台使用 jquery.ajax 并在调用时返回 jquery 承诺。

describe("Creating test record with incorrect data", ()=> {
    const params      = {tId:"12323","col":"colValue"};
    it('Should not create new record', (done) => {
        const result = Api.createRecord(params);
        console.log(result);
        expect(result)
            .to.eventually.equal(null)
            .notify(done);
    });
});

当我运行此代码时,出现以下错误。

  Error: done() invoked with non-Error: {"readyState":0,"status":0,"statusText":"SyntaxError"}
      at mightThrow (node_modules/jquery/dist/jquery.js:3583:29)
      at Window.process (node_modules/jquery/dist/jquery.js:3651:12)
      at Timeout.callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:524:19)

我无法找出问题所在。我的代码或其他地方是否有问题。

这就是我发送 ajax 请求的方式。

sendRequest(URL, dataToSend) {
    return $.ajax({
        type        : 'POST',
        url         : URL,
        crossDomain : true,
        data        : JSON.stringify(dataToSend),
        dataType    : 'json'
    }).fail((responseData) => {
        if (responseData.responseCode) {
            console.error(responseData.responseCode);
        }
    });
},

上面的代码中是否有一些问题是它处理失败而不是被抛出?

【问题讨论】:

    标签: javascript tdd mocha.js chai


    【解决方案1】:

    在仔细阅读 mocha 文档后,我终于找到了解决方案。

    在 Mocha v3.0.0 和更新版本中,返回一个 Promise 并调用 done() 将 导致异常,因为这通常是一个错误:

    const assert = require('assert');
    
    it('should complete this test', function (done) {
      return new Promise(function (resolve) {
        assert.ok(true);
        resolve();
      })
        .then(done);
    });
    

    我把我的测试用例改成了这个,它成功了。

    expect(result).to.be.rejected;
    

    【讨论】:

      猜你喜欢
      • 2016-12-30
      • 1970-01-01
      • 2017-04-08
      • 2015-02-17
      • 2013-02-10
      • 2018-05-10
      • 2015-12-28
      • 1970-01-01
      • 2015-07-16
      相关资源
      最近更新 更多