提问者:小点点

为什么sinon忽略了我对另一个函数的调用?


我在我的单元测试中使用了sinon间谍。我正在测试的函数调用了一次间谍函数,但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);
    })
});

来自西农的消息:

    < li>draughts应检测显示方法:AssertError:预期displayBoard将被调用一次,但在object . assert .[as called once](node _ modules \ sinon \ lib \ sinon \ assert . js:93:17)的fail assertion(node _ modules \ sinon \ lib \ sinon \ assert . js:67:25)的object . assert .[as called once](node _ modules \ sinon \ lib \ sinon \ assert . js:93:17)处被调用了0次。(test \ draughts . test . js:16:22)at processImmediate(internal/timers . js:461:21)

共1个答案

匿名用户

将draughts实现更改为类似这样的内容。

const draughts  = { initialise, displayBoard };
module.exports = draughts;

然后在初始化函数中,您可以使用< code > draughts . display board(board)调用displayBoard

这样,中国间谍就可以工作了。