【发布时间】:2021-06-16 19:17:57
【问题描述】:
我在单元测试中使用了 sinon spy。我正在测试的函数调用了一次间谍函数,但 sinon 坚持认为它根本没有调用它。
正在测试的代码:
const blank = ' '
const displayBoard = (board) => {
console.log('+-+-+-+-+-+-+-+-+-+');
console.log('| |0|1|2|3|4|5|6|7|')
console.log('+-+-+-+-+-+-+-+-+-+');
for (let row = board.length - 1; row > -1; row--) {
let r = `|${row}|`
for (let column = 0; column < 8; column++) {
r += board[row][column][1] + '|';
}
console.log(r);
console.log('+-+-+-+-+-+-+-+-+-+');
}
};
const initialise = () => {
let board = [];
board[0] = [['b', 'w'], ['w', blank], ['b', 'w'], ['w', blank], ['b', 'w'], ['w', blank], ['b', 'w'], ['w', blank]];
board[1] = [['w', blank], ['b', 'w'], ['w', blank], ['b', 'w'], ['w', blank], ['b', 'w'], ['w', blank], ['b', 'w']];
board[2] = [['b', 'w'], ['w', blank], ['b', 'w'], ['w', blank], ['b', 'w'], ['w', blank], ['b', 'w'], ['w', blank]];
board[3] = [['w', blank], ['b', blank], ['w', blank], ['b', blank], ['w', blank], ['b', blank], ['w', blank], ['b', blank]];
board[4] = [['b', blank], ['w', blank], ['b', blank], ['w', blank], ['b', blank], ['w', blank], ['b', blank], ['w', blank]];
board[5] = [['w', blank], ['b', 'b'], ['w', blank], ['b', 'b'], ['w', blank], ['b', 'b'], ['w', blank], ['b', 'b']];
board[6] = [['b', 'b'], ['w', blank], ['b', 'b'], ['w', blank], ['b', 'b'], ['w', blank], ['b', 'b'], ['w', blank],];
board[7] = [['w', blank], ['b', 'b'], ['w', blank], ['b', 'b'], ['w', blank], ['b', 'b'], ['w', blank], ['b', 'b']];
displayBoard(board);
return board;
};
module.exports = { initialise, displayBoard };
还有我的单元测试:
const draughts = require('../src/draughts');
const mocha = require('mocha');
const chai = require('chai');
const sinon = require('sinon');
const expect = chai.expect;
describe('draughts', ()=>{
it('should initialise board', ()=>{
result = draughts.initialise();
expect(result).to.be.an('array');
})
it('should spy the display method', ()=>{
let spy = sinon.spy(draughts, 'displayBoard');
draughts.initialise();
sinon.assert.calledOnce(spy);
})
});
来自诗乃的讯息:
- 草稿 应该监视显示方法: AssertError: 预期 displayBoard 被调用一次,但被调用了 0 次 在 Object.fail (node_modules\sinon\lib\sinon\assert.js:110:25) 在 failAssertion (node_modules\sinon\lib\sinon\assert.js:67:20) 在 Object.assert。 [as calledOnce] (node_modules\sinon\lib\sinon\assert.js:93:17) 在上下文。 (test\drafts.test.js:16:22) 在 processImmediate (internal/timers.js:461:21)
【问题讨论】:
标签: node.js unit-testing sinon