【问题标题】:Trying to use async/await in mocha尝试在 mocha 中使用 async/await
【发布时间】:2017-07-19 12:04:01
【问题描述】:

我想在 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

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

【问题讨论】:

  • 什么是 Babel 配置?它不会因为您安装了它而应用异步转换。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    截至 2017 年 4 月,使用“transform-async-to-generator”实际上会导致问题。

    一般来说,每个async 函数都会返回一个promise,或者将其返回值和异常转换为promise。测试 Promise 而不让你的测试调用 await 通常更干净:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2019-08-26
      • 2019-01-11
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多