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

问题描述 投票:1回答:1

我正在尝试测试使用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)
  }
}

它依赖于抛出APIErrors的两个辅助函数(我自己的错误类型)

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()
})

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

node.js testing node.js-tape
1个回答
1
投票

async function永远不会抛出错误......

...它返回一个可能因错误而拒绝的Promise

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

你需要add Promise support to tapetape-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!
});
© www.soinside.com 2019 - 2024. All rights reserved.