Ad

Jest & Enzyme | Received Value Must Be A Function, Received Undefined

I have a small function, that check if the name of a user is unique. See below:

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

I want to write some tests for it. But I get this error

Received value must be a function, but instead "undefined" was found

Can you explain to me what is wrong. I mean, this is an async function, and at the time it is undefined, but not sure what it wants me to do.

  it('Accept the data if the passed userName is unique', async () => {
    expect(await validateUsername('Username is unique')).not.toThrow();
  });
Ad

Answer

validateUsername returns a Promise that can reject with an Error...

...so test that the returned Promise either .resolves or .rejects as expected:

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

(Note that you need to throw an Error instead of just a string to check its message with toThrow)

Ad
source: stackoverflow.com
Ad