How to mock calls to JQuery without including JQuery in my spec file at all

北慕城南 提交于 2019-12-25 09:05:55

问题


The function I want to test is mostly pure JavaScript (CoffeeScript), but includes one line that calls Jquery:

$("input##{name}").change ->

I don't want to include Jquery in my Jasmine files at all. I'd like to mock it out completely so this is a pure unit test.

My spec for this function includes the following:

class $
  change: () ->
    return
spy = spyOn($, 'change')

However, Jasmine is giving me this error:

Error: change() method does not exist

How can I mock out $('input##{name}').change -> completely in Jasmine without include Jquery in the spec file?

Thanks.

UPDATE

Updating here as you can't format comments properly.

Inspired by the answers below, the contents of my it block now looks like this:

  window.$ = (selector) ->
    change: (callback) ->
  spy = spyOn(window.$, "change")
  ...
  expect(spy).toHaveBeenCalledTimes(9);

However, I am getting:

Error: change() method does not exist


回答1:


Note that there would be no $.change attribute even if you have included jQuery. $ is a function that returns an object with the change attribute. Try:

jQuerySelectorMock = jasmine.createSpyObj('jQuerySelectorMock', ['change'])
window.$ = -> jQuerySelectorMock
# test code
expect(jQuerySelectorMock.change).toHaveBeenCalledTimes(9)


来源:https://stackoverflow.com/questions/37832310/how-to-mock-calls-to-jquery-without-including-jquery-in-my-spec-file-at-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!