【问题标题】:Jasmine afterAll not called when error is thrown抛出错误时未调用 Jasmine afterAll
【发布时间】:2019-11-13 04:29:58
【问题描述】:

我正在使用 Jasmine 2.3.1。以下规范执行导致 afterAll 方法未被调用:

var http = require('http');

describe("simple server tests:", function() {

    afterAll(function(done) {
        console.log('after all');
    });

    it("throws an error because server is not running", function(done) {
        http.get("http://127.0.0.1:8080", function(res) {
            res.on('data', function(data) {
                done();
            });
        });
    });   
});

控制台显示:

[23:25:24] Starting 'test'...
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: connect ECONNREFUSED
    at exports._errnoException (util.js:746:11)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1010:19)

我的期望是调用 afterAll,而不管测试方法中抛出的错误如何。我真的不想在我的测试中尝试一下。如果这是 Jasmine 或我对 Jasmine 的使用有问题,请告诉我。

【问题讨论】:

    标签: javascript unit-testing jasmine


    【解决方案1】:

    afterAll 在所有规范都完成后被调用,但是你的情况服务器没有运行,因此done() 永远不会被调用。如果您正在测试服务器没有运行,我建议为请求添加一个错误处理程序并在其中执行done()

    var http = require('http');
    
    describe("simple server tests:", function() {
    
        afterAll(function(done) {
            console.log('after all');
            done(); // do not forget to execute done if you use it
        });
    
        it("throws an error because server is not running", function(done) {
    
            http.get("http://127.0.0.1:8080", function(res) {
                res.on('data', function(data) {
                    // never called
                })
            }).on('error', function(e) {
                console.log("Got error: " + e.message);
                done(); // finish async test
            });
        });
    });
    

    【讨论】:

    • 如果 done 没有被调用,那么我希望超时和 afterall 方法被调用。我的问题是任何测试都可能因语法错误或意外错误而失败。在这些情况下,毕竟没有被调用。即使抛出错误,我也希望在所有情况下都会调用 afterall。
    • 由于被测单元的异步行为,它以异常退出。 Jasmine 会捕获同步异常,但不会捕获异步异常,因为如果它是作用域,它们就会失效。您甚至可以尝试setTimeout(function () { a = b; }, 500); 并获得一个带有测试套件的ReferenceError。没有任何东西能捕捉到这个异常,因此整个套件都崩溃了。显然,如果套件已关闭,则无法调用 afterAll。我必须是known issue
    • 也许这个模块可以帮助你 - jasmine-async-errors.
    • 我认为这是一个已知问题。我已切换到正确处理此问题的摩卡咖啡。我尝试了异步错误(包装了 it 方法),但它没有用。如果 Jasmine 通过 done() 添加对异步测试的支持,我希望他们也能够处理错误。
    猜你喜欢
    • 2019-12-23
    • 1970-01-01
    • 2019-09-21
    • 2014-11-21
    • 2021-08-10
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多