To export arrow functions in React for unit testing with Jest, you can simply use export const functionName = () => {...}
syntax to declare and export your arrow function in the same file where your component is defined. For example:
import React from 'react';
export const sum = (a, b) => {
return a + b;
}
const MyComponent = () => {
return (
<div>
The sum of 2 and 3 is {sum(2, 3)}.
</div>
);
}
export default MyComponent;
In your test file, you can then import the arrow function separately and test it using the standard Jest syntax. For example:
import { sum } from './MyComponent';
describe('sum', () => {
it('adds 2 + 3 correctly', () => {
expect(sum(2, 3)).toEqual(5);
});
});
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-05-21 11:00:00 +0000
Seen: 15 times
Last updated: Feb 14 '22