簡體   English   中英

茉莉花:測試一個函數,使用茉莉花從另一個函數中調用

[英]Jasmine: Testing a function, being called from a different function using jasmine

我在javascript文件中有一種方法。

function foo() {
  setTimeout(function() {
      bar.getSomeUrl();
      },WAIT_FOR_SOMETIME);
}

現在, getSomeUrl()實現如下。

var bar = {
     getSomeUrl : function(){
         window.location.href = 'someUrl';
         return;
     },
     anotherProp : function() {
         return bar.getSomeUrl();
     }
};

我正在嘗試測試在調用foo()方法時將調用getSomeUrl() foo()方法。

我正在使用茉莉進行測試。 我的茉莉花測試如下:

describe('This tests getSomeUrl()', function() {
    it('is called when foo() is called', function(){
        spyOn(bar,'getSomeUrl').and.callFake(function(){});

        window.foo();
        expect(bar.getSomeUrl).toHaveBeenCalled();

    });
 });

我真的不關心測試getSomeUrl()內部發生的事情,因為我getSomeUrl()有單獨的測試。

我要測試的是,當我從某處調用foo()時,會調用getSomeUrl()

我有以下問題:

  1. 如果我這樣做,測試將失敗,並且在運行所有測試結束時,瀏覽器將重定向到someUrl 我沒想到會發生這種情況,因為我想,因為我對bar.getSomeUrl()有所監視,並且正在返回fake method因此在我調用window.foo()時實際上不會調用bar.getSomeUrl() window.foo()
  2. 所以我想可能是我應該按以下步驟操作:

    Expect(window.foo).toHaveBeenCalled();

這沒有任何意義,因為我正在嘗試測試是否正在調用bar.getSomeUrl()

但是,當我這樣做時,測試失敗,並且出現以下錯誤:

Error: Expected a spy, but got Function.

我還認為可能是導致問題的setTimeout函數,並將foo()函數更改為:

function foo() {
    bar.getSomeUrl();
};

沒有任何改變

我僅使用Jasmine和Javascript已有幾天,並且對工作原理有廣泛的了解。

非常感謝任何建議使該測試通過的建議,以及有關我做錯了什么的指針。

首先, bar.getSomeUrl應該是一個函數,而不是(無效的)對象

var bar = {
     getSomeUrl : function() {
         window.location.href = 'someUrl';
         return;
     },
     anotherProp : function() {
         return bar.getSomeUrl();
     }
};

其次,在測試帶有超時的代碼時,請使用Jasmine Clock

describe('This tests getSomeUrl()', function() {
    beforeEach(function() {
        jasmine.clock().install();
    });

    afterEach(function() {
        jasmine.clock().uninstall();
    });

    it('is called when foo() is called', function(){
        spyOn(bar,'getSomeUrl').and.callFake(function(){});

        foo();
        expect(bar.getSomeUrl).not.toHaveBeenCalled();

        jasmine.clock().tick(WAIT_FOR_SOMETIME);    
        expect(bar.getSomeUrl).toHaveBeenCalled();    
    });
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM