首页 > 解决方案 > 笑话和酶 | 接收到的值必须是函数,接收到未定义

问题描述

我有一个小功能,用于检查用户名是否唯一。见下文:

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

标签: reactjsunit-testingasync-awaitjestjsenzyme

解决方案


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


推荐阅读