Why does this Sinon mock have a mocking method that is not a function?

I would like to use test doubles in my coffeescript unit tests to help with problem sharing.

I use mocha sinon (in the context of a Rails application with konacha.)

I am trying to understand what at the moment seems straight from the documentation that has this example usage layout:

var myAPI = { method: function () {} }; var spy = sinon.spy(); var mock = sinon.mock(myAPI); mock.expects("method").once().throws(); PubSub.subscribe("message", myAPI.method); PubSub.subscribe("message", spy); PubSub.publishSync("message", undefined); mock.verify(); assert(spy.calledOnce); 

In my case, I am trying to make fun of a function call for an object as follows:

 canvas = sinon.mock getContext: (arg) -> canvas.expects("getContext").once() canvas.getContext('2d') canvas.verify() 

This gives a TypeError indicating that getContext not a function:

TypeError: canvas.getContext is not a function

The layout seems to be configured and checked correctly. If there is no call to getContext they tell me that the expectations were not met:

ExpectationError: expected getContext ([...]) once (never called)

Compiled JavaScript looks like this:

 var canvas; canvas = sinon.mock({ getContext: function(arg) {} }); canvas.expects("getContext").once(); canvas.getContext('2d'); canvas.verify(); 

What can explain this error?

I was wondering if I am doing something strange with a function argument, but I can reproduce it without an argument to call getContext .

+7
javascript unit-testing coffeescript mocking sinon
source share
1 answer

You are trying to directly call methods on a layout, but that is not how Sinon.JS thinks of ridicule. Consider the code example again:

 var myAPI = { method: function () {} }; var spy = sinon.spy(); var mock = sinon.mock(myAPI); mock.expects("method").once().throws(); PubSub.subscribe("message", myAPI.method); PubSub.subscribe("message", spy); PubSub.publishSync("message", undefined); mock.verify(); assert(spy.calledOnce); 

The myAPI object is myAPI , not mock . In the above example, the following will work:

 canvas_api = getContext: -> canvas_mock = sinon.mock(canvas_api) canvas_mock.expects("getContext").once() canvas_api.getContext() canvas_mock.verify() 
+9
source share

All Articles