笑话和酵素|接收到的值必须是一个函数,接收到的未定义

时间:2019-04-04 13:47:57

标签: reactjs unit-testing async-await jestjs enzyme

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

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

1 个答案:

答案 0 :(得分:1)

validateUsername返回的Promise可以被Error ...拒绝。

...因此测试返回的.resolves.rejects是预期的Promise

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检查其消息)