问题
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