簡體   English   中英

在mocha測試中使用es6

[英]Using es6 on mocha tests

我正在嘗試將es6合並到我的服務器端代碼中。 在運行服務器時使用babel-node工作,但是在運行mocha測試時我無法將es6編譯為es5代碼。

這是我的文件夾結構

我有一個server.js啟動一個worker.js文件(有快遞服務器)

server.js文件

import {SocketCluster} from 'socketcluster';

const socketCluster = new SocketCluster({
  workers:1,
  brokers:1,
  port: 3000,
  appName:null,
  workerController: __dirname + '/worker.js',
  brokerController: __dirname + '/broker.js',
  socketChannelLimit: 1000,
  crashWorkerOnError: true
})

worker.js文件

export const run = (worker) => {
  console.log(' >> worker PID: ',process.pid);

  const app = express();

  const httpServer = worker.httpServer;
  const scServer = worker.scServer;

  app.use(cookieParser())

  httpServer.on('request', app);

  app.get('/',(req,res) => {
    console.log('recieved')
    res.send('Hello world')
  })

}

手動運行服務器時,它適用於以下腳本

"start": "nodemon server/server.js --exec babel-node"

但是,當我嘗試使用mocha運行測試文件時,我得到一個'意外令牌'導出“錯誤”

(function (exports, require, module, __filename, __dirname) { export const run = (broker) => {
                                                              ^^^^^^
SyntaxError: Unexpected token export
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:511:25)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:456:32)
    at tryModuleLoad (module.js:415:12)
    at Function.Module._load (module.js:407:3)
    at Module.require (module.js:466:17)
    at require (internal/module.js:20:19)
    at initBrokerServer (/home/avernus/Desktop/projects/node-sc-react/node_modules/sc-broker/server.js:178:25)
    at process.<anonymous> (/home/avernus/Desktop/projects/node-sc-react/node_modules/sc-broker/server.js:498:9)

這是啟動mocha測試的腳本

"test": "mocha test/server/*.js --compilers js:babel-register"

我錯過了別的什么嗎?

這是測試文件

import server from '../../server/server';
import http from 'http';
import assert from 'assert';
import {expect} from 'chai';

describe('Express server',() =>{
  it('should return "Hello World"',() => {
    http.get('http://127.0.0.1:3000',(res) => {
      expect(res).to.contain('wtf world')
    })
  })
})

您需要使用Babel將測試腳本從ES2015ES5然后再將其傳遞給mocha來運行測試。 您可以按照以下方式在package.json添加/編輯測試腳本

...
"scripts": {
  "test": "mocha --compilers js:babel-core/register --recursive"
},
...

更新:

摩卡棄用了--compiler標志。 請查看此頁面以獲取更多信息。 新的npm腳本應如下所示

...
"scripts": {
  "test": "mocha --require babel-register --recursive"
},
...

結果我需要在我的server.js文件中指定一個initController ,以確保所有文件都是由babel編譯的。 這是我正在使用的websocket框架特有的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM