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
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad