【问题标题】:QUnit / Sinon test asynchronous ajax call throws exception if http errorQUnit/Sinon测试异步ajax调用如果http错误抛出异常
【发布时间】:2018-04-04 11:27:04
【问题描述】:

我有一段带有 jQ​​uery ajax 调用的代码,如果出现 http 错误,则会引发异常。

function Locale)() {
    $.ajax({
        url: this.endpoint,
        success: function(data) {
             //do stuff
            },
        error: function(jqxhr, error, serverException) {
            throw new httpErrorException(jqxhr, error, serverException);
        } 
   });
}

我的异常很好,很简单,可以确保它正常工作

httpErrorException = function(jqxhr, error, serverException) {
    this.toString = function() {
        return error + ': ' + jqxhr.status + ' ' + serverException
    }
}

我的测试如下

QUnit.test('test httpErrorException', function(assert) {
    assert.expect(1);
    server.respondWith('GET', '/fake/locale', [500, '', 'Internal Server Error']);
    var done = assert.async();
    assert.throws(
        function() {
            loc = locale(fakeUrl);
        },
        function(err) {
             return err.toString() === 'error: 500 Internal Server Error';
        },
        'it failed'
    );
    done();
});

当我运行测试时,我得到了

Uncaught it failed
Expected: function( a ){
    [code]
}
Actual: undefined

我一直在查看https://api.qunitjs.com/assert/throws 的 Qunit.throws 文档,看来我做的事情是正确的。我想这与异步调用有关,但我无法解决。

【问题讨论】:

    标签: javascript unit-testing exception qunit


    【解决方案1】:

    您的 throw 位于回调函数内部,因此它从那里抛出,不是来自您的 locale() 函数。您不能直接从异步调用中使用 throw/catch。您可以考虑使用 Promises,或在 error 回调中添加另一个函数调用。做任何你需要做的事情,然后在你的测试中模拟那个函数。

    (请注意,这是示例代码,我没有运行它...)

    在您的源代码中:

    function Locale() {
        $.ajax({
            url: this.endpoint,
            success: function(data) {
                 //do stuff
                },
            error: function(jqxhr, error, serverException) {
                handleErrors(jqxhr, error, serverException);
            } 
       });
    }
    

    function handleErrors(jqxhr, err, ex) { /* ... 做任何事... */ }

    然后在您的测试代码中:

    QUnit.test('test http errors', function(assert) {
        assert.expect(1);
        server.respondWith('GET', '/fake/locale', [500, '', 'Internal Server Error']);
        var done = assert.async();
    
        // really you should using something like Sinon to stub functions...
        function handleErrors(jqxhr, err, ex) {
            assert.strictEqual(jqxhr.status, 500);
            done();
        }
        Locale(fakeUrl);
    });
    

    请注意,这不是一个理想的设置...如果该 ajax 调用成功(当它应该失败时),您的测试将简单地超时。确实,您可能应该开始使用 Promises,但这可能暂时可行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多