无法将未定义或null转换为对象

Cannot convert undefined or null to object

本文关键字:转换 对象 null 未定义      更新时间:2023-09-26

不确定哪里出了问题:

test.js

let chai = require('chai'),
    should = chai.should(),
    game = require('../src/game');
    it('should be able to start the game', () => {
        game.start();
        game.started.should.be.true;
    });

game.js

var board = require('./board'),
    hasStarted = false;
module.exports = {
    start: start,
    started: hasStarted
};
function start(){
    hasStarted = true;
};

对于测试,我得到断言错误:

AssertionError: expected false to be true

我以为我已经在start()方法中设置了它,那么为什么我的测试仍然以false失败呢?

您已经为模块导出分配了hasStarted的初始值,它不会随着对start()的调用而改变。

使用函数而不是变量来检索,例如:

module.exports = {
    start: start,
    started: function() { return hasStarted; }
};

由于您使用的局部变量是基元类型,因此在调用start方法后不会反映。js中的基元类型是通过值传递的。

var hasStarted = {
    isStarted: false
};
var game = {
    start: start,
    started: hasStarted
};
function start() {
    hasStarted.isStarted = true;
};
module.exports = game;

如果您期望

,这将起作用