undefined 不是对象(正在计算 'Board.offsetWidth')

undefined is not an object (evaluating 'Board.offsetWidth')

我正在编写一个使用页面中的 canvas 的测试。当我尝试获取此对象的 offsetWidth 时,发生错误。如果我理解正确,问题是测试不知道从哪里获取 html 文件。

我的业力配置:

var webpackConfig = require('./webpack.config');
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai', 'sinon'],
files: [
  'src/index.pug',
  'test/**/*.ts'
],
exclude: [
],
preprocessors: {
  'test/**/*.ts': ['webpack'],
  'src/index.pug': ['pug', 'html2js']
},
webpack: {
  module: webpackConfig.module,
  resolve: webpackConfig.resolve
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: true,
concurrency: Infinity
})
}

你走在正确的轨道上。你需要有一个 DOM 可用,这意味着你要么需要 运行 在浏览器中进行测试,要么在 Node 中使用 JSDOM 创建一个假的浏览器环境。那部分还可以。

但是我们还没有看到您的任何测试。如果他们假设应该进行某种设置,例如将 Board 对象安装在某个 DOM 节点上,那么您需要在创建此新节点的测试之前进行设置阶段,将其添加到 DOM, 运行s Board 初始化代码等

编辑,得到代码: 所以 after looking at the code in question 我在 Board.ts 中找到了这一行:

this.canvasBoard = <HTMLCanvasElement>document.getElementsByClassName('game__board')[0];

这假设存在一个 DOM 节点和 class game__board。要使任何依赖于此的测试工作,您需要创建它(并在每次测试后清理它):

beforeEach(() => {
    const nodeNames = ['game__board', 'game__btn_play', 'game__btn_pause']; // add the rest ...
    nodeNames.forEach( (name) => {
        const elem = document.createElement('div');
        elem.classList.add(name);
        document.body.appendChild(elem);
     });
})

afterEach(() => {
    document.body.innerHTML = '';
});

上面的部分将创建所需的 canvas 节点,但另一件事是您的代码不正确 AFAIK。提到的行应该包含在 constructor 函数中,以便在创建对象时将其 运行 。

所以更改不正确的初始化代码

this.canvasBoard = <HTMLCanvasElement>document.getElementsByClassName('game__board')[0];

constructor() {
    this.canvasBoard = <HTMLCanvasElement>document.getElementsByClassName('game__board')[0];
}

您可以验证第一个 is incorrect on the TypeScript PlayGround