jasmine异步测试等待/运行超时

时间:2013-06-29 09:23:19

标签: unit-testing testing coffeescript jasmine phantomjs

我有一个函数可以将一些HTML加载到页面中,然后附加DOM元素和事件侦听器,并将变量loaded设置为true(用于测试目的)。它全部包含在父函数中,因此我可以传入参数并控制命名空间,我需要在返回对象中公开测试的函数。

((win) ->
    win.PanelLoader = (args) ->

        loaded = false

        el =
            container: $(".container")

        showPanel = ->
            $.get "panel.html", (data) ->
                el.container.append(data)
                attachDOMElements()
                loaded = true

        attachDOMElements = ->
            el.panel =  $(".panel")

        panelHasBeenLoaded = ->
            loaded

        showPanel()

        return {} =
            el:     el
            showPanel:  showPanel
) this

panelHasBeenLoaded()只返回false,直到AJAX请求成功。然后在我的spec文件中我有:

it "should confirm when the panel is loaded", ->
    panelLoader = PanelLoader()
    expect(panelLoader.el.panel).toBe(undefined)
    waitsFor (->
        panelLoader.panelHasBeenLoaded()
    ), "It took too long to load in the panel", 3000
    runs ->
        expect(panelLoader.el.panel.length).toBeGreaterThan(0)

我假设它正在初始化PanelLoader,确认没有'panel'DOM元素,那么waitsFor应该阻塞,直到`panelHasBeenLoaded()返回true,3秒后超时(应该是充足的)时间,运行localhost),然后它运行测试,期望DOM元素现在在那里。

我遇到的问题是它总是超时,导致第二次预期测试失败。当我在浏览器中测试时,这一切都正常工作,为什么我的单元测试不起作用?

我正在使用jasmine和phantom JS进行测试,通过grunt-contrib-jasmine跑步者。

感谢

1 个答案:

答案 0 :(得分:0)

您的代码存在的问题是Jasmine的waitsFor()仅适用于runs()块。 例如,

runs(function() {
        asyncMethod();
        console.log('an asynchronous method');
    }, 'an asynchronous method');

    waitsFor(function() {
        return x == 1;
    }, 'x to be equal to 1', 6000);

    console.log('this executes between two runs()');

    runs(function() {
        console.log('another sequential block');
    }, 'another sequential block');

表示在runs()之前不会执行第二个waitsFor(),但是console.log()没有嵌套在runs()中,而是在不等待的情况下执行。 我在代码中runs()之前没有看到waitsFor(),这就是为什么waitsFor()可能什么都不做。