【问题标题】:Trying to import object in Webpack for testing, I'm lost试图在 Webpack 中导入对象进行测试,我迷路了
【发布时间】:2019-03-23 14:55:10
【问题描述】:

我正在做一个课堂项目,但我对 webpack 和 chai/mocha 测试感到迷茫。

  • 我有一个对象,其中包含名为 gameData 的数组,该对象位于名为 data.js 的文件中。

  • 我正在使用export default gameData 导出gameData 变量。

  • 我将它导入到我的 Game.js 文件中,该文件有一个名为 Game 的类。

我可以使用什么方法让我的 Game 类访问我的 data.js 文件中的 gameData 对象,以及如何测试我的类是否可以访问 gameData?

如果这是一个愚蠢的问题,我们深表歉意,但目前处理 webpack 和单元测试对我来说还是很新鲜的。

import './data.js';

class Game {
  constructor(){
    this.currentTurn = 'p1';
    this.game = gameData;
  }
  startGame(){
    //import the data structures
    //copy the data structures
    //select 1 survey at random and remove it from the source array
    //append the question to the DOM
    //create a array with the three associated answers and remove them from source array
  }
  restartGame(){
    //clear all fields
    //revert back to starting arrays
  }
  whoseTurn(){
    if (this.currentTurn === 'p2'){
      //inputs and fields should reflect that it's players X's turn
      //player Y disabled
    } else {
      //inputs and fields should reflect that it's players Y's turn
      //player X disabled
    }
  }
}




export default Game;
import chai from 'chai';
import Game from '../src/Game.js';
import '../src/data.js';
const expect = chai.expect;

describe('Game', function() {
    it('Should have access to the data structures', function() {
        let game = new Game();
    })
}

测试错误:

1) Game
       Should have access to the data structures:
      ReferenceError: gameData is not defined
      at new Game (dist/webpack:/src/Game.js:6:1)
      at Context.<anonymous> (dist/webpack:/test/Game-test.js:8:1)

【问题讨论】:

    标签: javascript webpack mocha.js chai


    【解决方案1】:
    import gameData from './data.js'
    

    或者您可以将 gameData 导出到 data.js 中的全局。 如果您在浏览器中,请设置window.gameData=gameData 或者如果你在 node.js 中,设置global.gameData=gameData

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 2012-03-08
      • 1970-01-01
      • 2012-03-29
      • 2016-02-26
      • 2016-12-25
      • 2017-09-30
      相关资源
      最近更新 更多