如何在挂钩前在 mocha 中使用 async/await?

How do I use async/await in a mocha before hook?

我正在使用节点的 util.promisify 尝试在辅助函数中等待 fs.readFile 结果,但从未调用第二个 readFile 并且我总是遇到超时错误。

根据 the Mocha docs and this blog post 对 promisify 效用函数的解释,据我所知,我正在正确使用 await。

// mocha setup.js file
const { readFile } = require('fs')
const { promisify } = require('util')

module.exports = {
  readFile: promisify(readFile)
}
// test-file.js
const { assert } = require('chai')
const { readFile } = require('./setup')
const { CustomWordList, Spelling, Word } = require('../src/classes')
const nspell = require('nspell')

describe('Spelling Class', function () {
  const content = 'A colorful text that should be colorful cleaned during Spelling class instantiation! 1337'
  let dictionary
  let speller
  let obj

  before(async function () {
    this.timeout(5000)
    dictionary = await loadDictionary('en-au')
    speller = nspell(dictionary)
    obj = new Spelling(speller, content)
  })

  it('should assert object is instance of Spelling', function () {
    assert.instanceOf(obj, Spelling)
  })

  // read dictionary aff and dic files from disk and return an dictionary object
  const loadDictionary = async (filename) => {
    const dict = {}
    await readFile(`dictionaries/${filename}.dic`, 'utf8', (err, data) => {
      if (err) console.log(err)
      if (data) {
        dict.dic = data
        console.log('got dic data')
      }
    })
    await readFile(`dictionaries/${filename}.aff`, 'utf8', (err, data) => {
      if (err) console.log(err)
      if (data) {
        dict.aff = data
        console.log('got aff data')
      }
    })
    return dict
  }
})

超时错误是标准的“超时...确保调用 done() 或确保 Promise 解析”。我注意到如果第一个 readFile 正在读取 .dic 文件,控制台将输出“got dic data”,但如果交换 readFile 操作,控制台输出是“got aff data”。

这表明由于某种原因只有第一个 readFile 被执行,但我不知道为什么第一个 readFile 会阻止第二个读取文件的执行(因此 return 语句从运行).

感谢您的宝贵时间。

你做错了。在 promise 之后,你的 readFile 函数将 return 一个 Promise 代替,你可以使用 async/await 来处理这个。如果您使用回调,那么您不需要承诺。

这是用 async/await 编写的 loadDictionary 函数。

const loadDictionary = async (filename) => {
    const dict = {}

    try {
        const data = await readFile(`dictionaries/${filename}.dic`, 'utf8');
        if (data) {
            dict.dic = data
            console.log('got dic data')
        }
    } catch (err) {
        console.log(err)
    }

    try {
        const data = await readFile(`dictionaries/${filename}.aff`, 'utf8');
        if (data) {
            dict.aff = data
            console.log('got aff data')
        }
    } catch (err) {
        console.log(err)
    }

    return dict
}