0

Is there a way to import a function from a react component into a test file?

for example:

component:

const funcToExport = () => {
      let a = 1;
      let b = 2;
      let value = a + b;
      return value
}

test file:

import funcToExport from './component';

can this be done, so you can use the function in the test file?

Sole
  • 3,100
  • 14
  • 58
  • 112
  • you can read about import/export [here](https://stackoverflow.com/questions/49616639/how-can-i-export-all-functions-from-a-file-in-js) and this [question](https://stackoverflow.com/questions/49616639/how-can-i-export-all-functions-from-a-file-in-js) can helps you. – clay Feb 23 '22 at 16:49

1 Answers1

0

Yes you can use the keyword "export" to your function then import it in other files. There are two different types of export:

Named Export:

export const funcToExport = () => {
      let a = 1;
      let b = 2;
      let value = a + b;
      return value
}

Import:

import { funcToExport } from "/file-path"

Default Export

const funcToExport = () => {
      let a = 1;
      let b = 2;
      let value = a + b;
      return value
}
export default funcToExport;

Import:

import funcToExport from "/file-path"

For more info check: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

Ossama Ismaili
  • 435
  • 1
  • 11
  • just an addon, you will need to import it like ```import {funcToExport} from './component';``` – DevX Feb 24 '22 at 03:16