CodeG
CodeG

Reputation: 467

Jest error -- Cannot read property 'get' of undefined

I have the configuration of a service inside a component in React and I am having problems with jest and testing-library, the app is working but the test is blocking.

  import { appSetupConfig } from '.../myapp'
  import theConfig from '.../config'

  useEffect(() => {
    const allowAppInstance = appSetupConfig();

    allowAppInstance.get(theConfig).then((value) => {
       if (value.something) {
           Do Something;
       } 
    ...the rest of code

  }, []);

This theConfig is an external file containing an object. This is the error:

  TypeError: Cannot read property 'get' of undefined

  37 |     const allowAppInstance = appSetupConfig();
  38 | 
> 39 |     allowAppInstance.get(theConfig).then((value) => {

Is there any way to mock this get in jest's setup.js? I don’t necessarily need to test this item yet, but I can’t proceed without it.

Upvotes: 2

Views: 16179

Answers (1)

kdau
kdau

Reputation: 2099

Yes, there is. So it would seem that you have called jest.mock('.../myapp') or similar at some point. In the mock object that Jest creates for the module, every mock function returns undefined. You need to mock a return value on appSetupConfig that is itself a mock object with the method(s) you need like get. Then get in turn needs to return a mock promise, and so on as deeply as needed. In your setup file, this would look like:

import { appSetupConfig } from '.../myapp'
...
jest.mock('.../myapp');
appSetupConfig.mockReturnValue({
  get: jest.fn().mockResolvedValue({ something: jest.fn() }),
});

Your .then block will then be called in the test(s) with value set to undefined, but you can mock a different resolved value or a rejection of the promise for particular tests.

Upvotes: 5

Related Questions