使用jquery promise测试代码时的Mocha测试错误

时间:2017-04-27 17:12:31

标签: javascript tdd mocha chai

我正在尝试测试以下代码。基本上,服务器拒绝此请求,因为某些参数未按照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);
        }
    });
},

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

1 个答案:

答案 0 :(得分:0)

最后,在仔细阅读了mocha docs后,我找到了解决方案。

  

在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;