Sinon:测试函数调用和var变化的顺序
Sinon: Test the order of function call and var change
当我们有
// arrange
var testVar = 0;
var testFunction = sandbox.stub();
// act
TestClass.TestMethod(); // it changes testVar and calls testFunction
有没有办法在调用 testFunction 之前测试 testVar 是否已更改?
编辑: 好像没有。但!如果变量是一个对象 属性,您可以做类似的事情。在下面检查我自己的答案。
好吧,看来真的做不到了。
不过,我确实找到了一种使用对象属性进行测试的方法。示例伪代码:
before(function() {
var functionCallOrder = [];
document.body.classList.add = function() {
functionCallOrder.push('added class');
};
Object.defineProperty(document.body, 'scrollTop', {
set: function() {
functionCallOrder.push('changed viewport location');
}
});
it('should set a class before changing the viewport location'), function() {
// act
MyModule.methodThatDoesWhatTheDescriptionSays();
// assert
expect(functionCallOrder).to.deep.equal([
'added class',
'changed viewport location'
]);
});
});
当我们有
// arrange
var testVar = 0;
var testFunction = sandbox.stub();
// act
TestClass.TestMethod(); // it changes testVar and calls testFunction
有没有办法在调用 testFunction 之前测试 testVar 是否已更改?
编辑: 好像没有。但!如果变量是一个对象 属性,您可以做类似的事情。在下面检查我自己的答案。
好吧,看来真的做不到了。
不过,我确实找到了一种使用对象属性进行测试的方法。示例伪代码:
before(function() {
var functionCallOrder = [];
document.body.classList.add = function() {
functionCallOrder.push('added class');
};
Object.defineProperty(document.body, 'scrollTop', {
set: function() {
functionCallOrder.push('changed viewport location');
}
});
it('should set a class before changing the viewport location'), function() {
// act
MyModule.methodThatDoesWhatTheDescriptionSays();
// assert
expect(functionCallOrder).to.deep.equal([
'added class',
'changed viewport location'
]);
});
});