试图在mocha中使用async / await

时间:2017-02-28 13:28:30

标签: node.js async-await mocha ecmascript-2017

我想在mocha中使用async / await来进行测试。我看过很多帖子,但我找不到解决方案。我已经安装了所有的babel模块以便编写代码,但它不起作用。

这是我在" test"中的代码。文件夹:

import test from 'mocha'
import 'babel-polyfill'
import { expect } from 'chai'
import { assert } from 'chai'
import utils from '../lib/utils'

describe('long number', function () {
  it("Sample", mochaAsync(async () => {
    var x = utils.longNums(0);
    expect(x).to.equal(5000);
  }))
})

这是我的package.json,我正在使用我已阅读的所有babel依赖项和插件,我必须安装,我的测试脚本,我建议mocha使用babel转换

   {
     "name": "pos_lisa-test",
     "version": "1.0.0",
     "description": "pos lisa test",
     "main": "index.js",
     "scripts": {
       "test": "mocha --compilers js:babel-core/register ./src/**/*.test.js"
     },
     "standard": {
       "parser": "babel-eslint"
     },
     "babel": {
       "presets": [
         "es2015",
         "react"
       ]
     },
     "keywords": [
       "test"
     ],
     "author": "Mauricio",
     "license": "MIT",
     "devDependencies": {
       "babel-core": "^6.23.1",
       "babel-eslint": "^7.1.1",
       "babel-plugin-transform-async-to-generator": "^6.22.0",
       "babel-preset-es2015": "^6.22.0",
       "babel-preset-react": "^6.23.0",
       "chai": "^3.5.0",
       "mocha": "^3.2.0",
     },
     "plugins": [
       "transform-async-to-generator"
     ],
     "dependencies": {
       "babel-polyfill": "^6.23.0"
     }
   }

我得到的错误如下

it('should remove items that don\'t evaluate to true when passed to predicate function', async function () {
                                                                                           ^^^^^
SyntaxError: missing ) after argument list

我做错了什么?提前感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您已将"plugins": ["transform-async-to-generator"]"添加到package.json的顶层,但它应位于"babel"部分内。将其更改为:

"babel": {
  "presets": [
    "es2015",
    "react"
  ],
  "plugins": [
    "transform-async-to-generator"
  ]
},

答案 1 :(得分:0)

根据Javascript之道,“代码在当下流动,所以知识只是一个提示,就像流的地图一样。”

截至2017年4月,拥有'transform-async-to-generator'实际上会导致问题。

更一般地说,每个async函数都会返回一个promise,或者将其返回值和异常强制转换为promise。测试承诺通常更干净,而没有测试await

it('should have no drops left', () => 
  ocean.listDrops().should.eventually.have.length(0));