admin管理员组

文章数量:1323354

I'm trying to test code using Sinon.js, but I'm unfamiliar with out it's supposed to behave.

I expect that I can create a 'fake' object, wrap it with sinon and pass it to whatever I'm testing, and have it do its thing. However, it seems like every time I try to wrap a sinon object, the function is not there:

var event_api = {
  startTime: function() {
    return '123';
  }
}

var stub = sinon.stub(event_api);
console.log(stub.startTime()) // returns undefined
var mock = sinon.mock(event_api);
console.log(mock.startTime()) // returns undefined

What am I missing?

I'm trying to test code using Sinon.js, but I'm unfamiliar with out it's supposed to behave.

I expect that I can create a 'fake' object, wrap it with sinon and pass it to whatever I'm testing, and have it do its thing. However, it seems like every time I try to wrap a sinon object, the function is not there:

var event_api = {
  startTime: function() {
    return '123';
  }
}

var stub = sinon.stub(event_api);
console.log(stub.startTime()) // returns undefined
var mock = sinon.mock(event_api);
console.log(mock.startTime()) // returns undefined

What am I missing?

Share Improve this question asked Jan 8, 2014 at 3:59 JamesJames 6,50911 gold badges61 silver badges87 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

It depends on what are you trying to do:

If you don't have any expectations on the call then you should use a stub, for example startTime() only has to return a value.

var event_api = {
  startTime: sinon.stub().returns('123')
}

console.log(event_api.startTime());

But if what you want is to set some assertions for the call, then you should use a mock.

var event_api = {
  startTime: function() {
    return '123';
  }
}

//code to test
function getStartTime(e) {
  return e.startTime();
}

var mock = sinon.mock(event_api);
mock.expects("startTime").once();

getStartTime(event_api);
mock.verify();

Hope this helps.

The function is indeed there, but it's void of any functionality, since it has been stubbed. If you want to log the function itself in the console, you have to execute:

console.log(stub.startTime)   //logs the function itself

instead of:

console.log(stub.startTime())   //logs the result of the function, which is undefined

However, as said, all the methods of a stub object have been "emptied" of their functionality. If you want to make a method of a stubbed object return a value, you can do the following:

var stub = sinon.stub(event_api);
stub.startTime.returns(123);
console.log(stub.startTime)    //log the function
console.log(stub.startTime())    //log the result of function, that is now 123

本文标签: javascriptCreating test objects in SinonjsStack Overflow