尝试在Webpack中导入对象以进行测试,我迷路了

时间:2019-03-23 14:55:10

标签: javascript webpack mocha chai

我正在为一个课堂项目工作,但是我对webpack和chai / mocha测试一无所知。

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

  • 我正在使用gameData导出export default 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)

1 个答案:

答案 0 :(得分:0)

import gameData from './data.js'

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