我正在尝试测试使用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(我自己的Error类型)的两个帮助器函数
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`)
}
我已经尝试了这个Tape测试,但都失败了,没有发现错误
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永远不会抛出错误...
...它返回一个Promise
可能会拒绝并显示错误。
因此,对返回的Promise
进行测试,以验证其是否拒绝并出现预期的错误。
您需要使用add Promise
support to tape
之类的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!
});
关于node.js - 如何使用Tape测试异步函数抛出错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55694819/