0

Im getting error in my unit test which is cannot read property 'setValue' of undefined. Is it mean I need to mock the function. How to do it? I mock like this, but still got the error.

function.js

const aStr = "a";
const bStr = "b";
const cStr = "c";
const dStr = "d";

export default class mainFunction{

 setValue = (a,b,c,d) =>  {
   this.setA(a);
   this.setB(b);
   this.setC(c);
   this.setD(d);
 }

 setA = (a) => sessionStorage.setItem(aStr, a);
 setB = (b) => sessionStorage.setItem(bStr, b);
 setC = (c) => sessionStorage.setItem(cStr, c);
 setD = (d) => sessionStorage.setItem(dStr, d);

}

main.js

    import func from './function.js';
    import React, {useEffect,useState} from "React";
        
    const form = (props:any) => {
    
        const onsubmit = ()  => {
          func.setValue('aValue','bValue','cValue','dValue');
        }
        
        return(
          <div>
           <button onClick='onsubmit'>submit</button>
          </div>
        )
    }

export default form;

main.spec.js

import func from '.function.js';
import main from '.main.js';

jest.mock('./function.js',() =>  ({
  setValue:() => ({})
}))

describe('unit test : ', () => {
  const mock = jest.fn()
  await act(async() => {
    const {container} =render(<main onClick={mock}/>);
  })
})
Lin Du
  • 88,126
  • 95
  • 281
  • 483
syareen
  • 328
  • 2
  • 4
  • 15
  • I've answered a similar question [here](https://stackoverflow.com/a/72161842/9632621). The gist is that by the time you mock the `function.js` module, **it has already been imported**. In the linked post you can find the steps that should solve this problem. – Andrei Gătej May 30 '22 at 19:43

1 Answers1

0

Have you tried using mockImplementation to mock the class?

import func from '.function.js';
import main from '.main.js';

jest.mock('./function.js');

func.mockImplementation(() => ({
  setValue:() => ({})
}));

Alan Friedman
  • 1,582
  • 9
  • 7