如何使用Jasmine JS拦截简单的jQuery函数?

时间:2013-10-12 21:25:50

标签: javascript coffeescript jasmine

我在生产代码中有这个:

$(document).ready ->      
  if $( "#accordion" ).length > 0
    $( "#accordion" ).accordion()

哪个有效,我想测试一下:

describe "Non-MVCd stuff", ->
  beforeEach ->
    spyOn( $('#accordion').prototype, 'accordion' )
    if $("#accordion").length > 0 
      $("#accordion").accordion()

  describe "accordion", ->
    it 'works', ->
      expect( $('#accordion' ).length ).toBe( 1, 'the element must be there.' )
      expect( $('#accordion').prototype.accordion ).toHaveBeenCalled()

我收到此错误:

spyOn could not find an object to spy upon for accordion()
TypeError: $(...).prototype is undefined in http://pi.local:3011/assets/spec/views/utils_spec.js?body=1 (line 14)

没有原型它也不起作用(和$(“#accordion”)。原型未定义):

describe "Non-MVCd stuff", ->
  beforeEach ->
    spyOn( $('#accordion'), 'accordion' )
    if $("#accordion").length > 0 
      $("#accordion").accordion()
  describe "accordion", ->
    it 'works', ->
      expect( $('#accordion' ).length ).toBe( 1, 'the element must be there.' )
      expect( $('#accordion').accordion ).toHaveBeenCalled()

_

Error: Expected a spy, but got Function. in http://pi.local:3011/assets/jasmine-1.1.0/jasmine.js?body=1 (line 1286)

1 个答案:

答案 0 :(得分:0)

只需使用以下代码来监视对象函数,就像这样。

spyOn($.fn, 'accordion' )

或者正常方法。

spyOn([ObjectName].prototype, '[methodName]' )