在Sinon.js中创建测试对象

Jam*_*mes 4 javascript testing sinon

我正在尝试使用Sinon.js测试代码,但我不熟悉它应该表现的行为。

我希望我可以创建一个“假”对象,用sinon包裹它,并将其传递给我正在测试的任何对象,并使其起作用。但是,似乎每次我尝试包装一个sinon对象时,该函数都不存在:

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
Run Code Online (Sandbox Code Playgroud)

我想念什么?

小智 5

这取决于您要做什么:

如果对调用没有任何期望,则应使用存根,例如,startTime()仅必须返回一个值。

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

console.log(event_api.startTime());
Run Code Online (Sandbox Code Playgroud)

但是,如果您要为调用设置一些断言,则应该使用模拟。

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();
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。