Ask Your Question
0

How can arrow functions in React be exported for unit testing with Jest?

asked 2021-05-21 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-02-14 02:00:00 +0000

woof gravatar image

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);
  });
});
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-05-21 11:00:00 +0000

Seen: 15 times

Last updated: Feb 14 '22