如何使用 Tape 测试异步函数抛出错误?

How do I test asynchronous function throwing error with Tape?

我正在尝试使用 Tape 测试调用 API 的异步函数,但我似乎不太走运。我以前用过 Mocha/Chai 和 Jasmine,但我不确定如何在这里做我想做的事。

这是我要测试的功能

const logicGetMovies = async (genre, page) => {

  numCheck(genre, 'genre')
  numCheck(page, 'page')
  stringCheck(process.env.API_KEY,'process.env.API_KEY')

  const url = `https://api.themoviedb.org/3/discover/movie?with_genres=${genre}&api_key=${process.env.API_KEY}&page=${page}&sort_by=vote_average.desc`

  try {
    return await axios.get(url)
  } catch (e) {
    throw new APIError(e.message)
  }
}

它依赖于两个抛出 API错误(我自己的错误类型)

的辅助函数
const numCheck = (num, name) => {
  if (!num) throw new APIError(`${name} is missing`)
  if (typeof num !== 'number' || num <= 0) throw new APIError(`${name} must be a number greater than 0`)
}

const stringCheck = (string, name) => {
  if (!string) throw new APIError(`${name} is missing`)
  if (typeof string !== 'string') throw new APIError(`${name} must be of type string`)
}

我试过这个磁带测试,但它都失败了,而且没有发现错误

const test = require('tape')
const logic = require('../../logic')
const APIError = require('../../logic/APIError')

test('getMovies should throw error with missing genre',(t) =>{
  t.throws(logic.logicGetMovies(null,1),APIError,'genre is missing')

})

我尝试将其更改为 async,但没有用。

const test = require('tape')
const logic = require('../../logic')
const APIError = require('../../logic/APIError')

test('getMovies should throw error with missing genre', async (t) => {
  t.throws(logic.logicGetMovies(null, 1), APIError, 'genre is missing')
  t.end()
})

显然我在这里迷路了。任何线索或答案将不胜感激!

async function 从不抛出错误...

...它 returns 一个 Promise 可能会因错误而拒绝。

因此测试返回的 Promise 以验证它是否拒绝并出现预期的错误。

您需要 add Promise support to tape with something like tape-promise

这是一个简化的例子:

const tape = require('tape');
const _test = require('tape-promise').default;
const test = _test(tape);

const func = async () => {
  throw new Error('the error');
};

test('should reject', async (t) => {
  await t.rejects(func(), Error, 'the error');  // Success!
});

这是我测试异步错误抛出的方式:

test('fetchData()', async (t) => {
  try {
    await fetchData();
    t.fail('it should throws an error');
  } catch (e) {
    t.pass('it should throws an error');
  }
}

如果抛出错误,catch 块将捕获错误并生成通过的测试。

否则,t.fail()将被执行并产生一个失败的测试。