Search code examples
javascriptjestjsbabeljsbabel-jest

How to use functions from different part of my code in jest testing?


I'm trying to write a test in jest. I have 2 functions in a different js file that i need to use in order to pass data to the function im testing.

i tried to use:

  1. import {func} from './funcfile' gives: SyntaxError: Cannot use import statement outside a module
  2. const {func} = require('./funcfile') gives: SyntaxError: Unexpected token 'export'

looking at other topics and google, tried every dependency installation and added configurations to package.json, jest.config.js, .babelrc, babel.config.js.

the only thing that happened is getting an error around type ErrorHandler = ... where it says a syntax error again excepted ";"

i reverted everything therefore i don't have the files with the changes, willing to try any solution you may seem fit. the line where the error points to

require code on jest file

it crashes on export const phone_number and never event get to the getSubCategory export line....

Edit:

Been asked to add some more code so others could understand better, Thing is there is not much more code. I have a file with lots of export const = ; (as described in photo) and eventually the function export const (as described in photo)

on my jest file i just have the import/ require line I added and the test fails there.

the error i get when using the suggested answer : enter image description here


Solution

  • You can import your utils class and use constants as properties of this exported module, e.g.

    import * as UTILS from './utils';
    
    ...
    
    UTILS.getSubCategoryId('return input')
    

    where utils is

    export const getSubCategoryId = (category) => category;
    

    Please check example https://stackblitz.com/edit/typescript-rujqvm?file=index.ts