reactjs - 笑话和酶 | 接收到的值必须是函数,接收到未定义
问题描述
我有一个小功能,用于检查用户名是否唯一。见下文:
export const validateUsername = value =>
listUsers({ once: true }).then(({ data }) => {
if (Array.isArray(data) && data.find(userData => userData.username === value)) {
// eslint-disable-next-line no-throw-literal
throw 'Username already exists';
}
});
我想为它写一些测试。但我得到这个错误
Received value must be a function, but instead "undefined" was found
你能向我解释什么是错的。我的意思是,这是一个异步函数,当时它是未定义的,但不确定它要我做什么。
it('Accept the data if the passed userName is unique', async () => {
expect(await validateUsername('Username is unique')).not.toThrow();
});
解决方案
validateUsername
返回Promise
可以用Error
...拒绝的 a
...所以测试返回Promise
或按预期返回:.resolves
.rejects
const listUsers = async() => Promise.resolve({data: [{ username: 'existing username' }]});
export const validateUsername = value =>
listUsers({ once: true }).then(({ data }) => {
if (Array.isArray(data) && data.find(userData => userData.username === value)) {
// eslint-disable-next-line no-throw-literal
throw new Error('Username already exists'); // <= throw an Error instead of just a string
}
});
it('Accept the data if the passed userName is unique', async () => {
await expect(validateUsername('Username is unique')).resolves.not.toThrow(); // Success!
});
it('throws error if username already exists', async () => {
await expect(validateUsername('existing username')).rejects.toThrow('Username already exists'); // Success!
});
(请注意,您需要抛出一个Error
而不仅仅是一个字符串来检查它的消息toThrow
)
推荐阅读
- java - 函数对象的内部类中的变量/对象会发生什么?
- php - PHP 错误:警告:openssl_decrypt(): Unknown cipher algorithm
- python - Openpyxl,如何遍历工作表以在每个工作表中添加图像?
- javascript - 从 html 记录用户的输入并保存在文件/数据库中
- sql - XML 到 SQL - SQL Server
- bash - Bash 脚本创建具有相同内容的单独文件
- javascript - Angular中多个组件的层次结构?
- winston - Winston Colorizer 投掷错误
- apache-spark - 在 Java 中使用 dataset.persisit() 和 dataset.unpersist()
- batch-file - 批处理程序无故退出且无错误