测试脚本加载后是否调用函数

时间:2014-09-15 12:55:11

标签: javascript testing jasmine karma-runner

我有一个要测试的javascript文件,它以行结束:

window.vioInit && setTimeout(window.vioInit, 0);

因此,在加载脚本后,它会调用函数vioInit(如果存在)。我想用测试来报道这个案例。我使用karmajasmine。现在我有下一个规范:

describe("VIO initialization. ", function() {
    window.vioInit = new Function();

    beforeEach(function() {
        window.vioInit = new Function();
        spyOn(window, 'vioInit');
    });

    it("window.vioInit() should be called on script load", function() {
        expect(window.vioInit).toHaveBeenCalled();
    });
});

但输出失败了:

E:\webdev\hapi>karma start karma.conf.js
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Windows 7)]: Connected on socket ttEs4AgYPQxCUB_-XG43 with id 8200833

PhantomJS 1.9.7 (Windows 7) VIO initialization.  window.vioInit() should be called on script load FAILED
        Expected spy vioInit to have been called.
PhantomJS 1.9.7 (Windows 7): Executed 1 of 1 (1 FAILED) ERROR (0.013 secs / 0.003 secs)

那么如何在加载脚本之前在window.vioInit上设置间谍并检查脚本加载后是否调用了它?

1 个答案:

答案 0 :(得分:0)

经过几个小时的调试后,我进入了下一个解决方案:

describe("VIO initialization. ", function () {
    window.vioInit = jasmine.createSpy("vioInit spy");

    beforeEach(function (done) {
        setTimeout(function(){
            // waiting for vioInit to be called
            done();
        }, 10)
    });

    it("window.vioInit() should be called on script load", function (done) {
        expect(window.vioInit).toHaveBeenCalled();
        done();
    });
});

另请注意,在karma配置中,您的测试规范必须包含在源代码之前:

module.exports = function (config) {
    config.set({
        // ...
        // list of files / patterns to load in the browser
        files: [
            'hapi/public/partner_fe/tests/**/*.js',
            'hapi/public/static/partner/vio-api.js'
        ],
        // ...
    });
};

文档:Jasmine Asynchronous SupportJasmine SpiesKarma Configuration File