2016-12-28 120 views
0

我在JavaScript文件中有一个方法。Jasmine:测试函数,使用jasmine从不同的函数调用

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()方法将被调用。

我正在使用茉莉花进行测试。我的茉莉花测试如下:

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()内部发生的,因为我有一个单独的测试。

我试图测试的是,当我从某处调用我的foo()时,getSomeUrl()被调用。

我有以下问题:

  1. 如果我做这样的测试失败,并在运行所有测试结束后,将浏览器重定向到someUrl。我没想到会发生这种情况,因为我认为自从我在bar.getSomeUrl()上有一名间谍,并且正在返回fake method,所以当我拨打window.foo()时,实际上并不会调用bar.getSomeUrl()
  2. 所以我想可能是我应该做的,如下:

    预期(window.foo).toHaveBeenCalled();

这没有意义,因为我试图测试bar.getSomeUrl()被调用。

但是我这样做的时候,测试失败,我得到了以下错误:

Error: Expected a spy, but got Function.

我还以为这可能是setTimeout功能,导致该问题,改变了foo()功能:

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

没有任何改变

我一直与茉莉e和Javascript,现在只有几天,并且对事情的工作有广泛的理解。

任何建议,使这个测试通过,也是一个指针,我做错了什么是非常感谢。

+0

它不是java相关的。 JavaScript拼写一个词,并与Java没有任何关系。 –

+0

照顾到了这一点。谢谢。 – ChillBan123

+0

你有一个语法错误。 'bar.getSomeUrl'是一个对象文字(语法无效)。这不是一个功能 – Phil

回答

0

首先,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();  
    }); 
}); 
+0

谢谢。我已经实现了'bar.getSomeUrl'作为一个函数。发布问题时发生错字。 – ChillBan123

+0

试过这个建议。没有帮助。仍然最终重定向到'someUrl'。 – ChillBan123

+0

好吧,我在浏览器中调试测试运行器,发现我收到一个异常: '模拟时钟未安装.' 我做了一个项目重建并重试,似乎一切正常。谢谢@Phil。那么由于setTimeout函数调用,测试失败了吗? – ChillBan123

相关问题