CodeG
CodeG

Reputation: 467

Jest TypeError: Cannot read property of null

I have a setup for an external application and start it within a const, then put it in the const allowAppInstance the configuration of the appConfig

export const setupRemote = () => {
  if (isRemoteAvailable) {
    try {
      ...

      const allowAppInstance = SetupConfig.start(remoteInstance);

      return {
        allowAppInstance,
      };
    } catch (e) {
      console.error(e);
    }
  }
};

here I export

export const appSetupConfig = () => setupRemote().allowAppInstance;

in the component, I get this setup and put it in a const

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

      useEffect(() => {
        const allowAppInstance = appSetupConfig();
    
        ...the rest of code
    
      }, []);

the application works, but when I run the tests, jest doesn't let it pass, it causes this error:

  TypeError: Cannot read property 'allowAppInstance' of null

  43 | };
  44 | 
> 45 | export const appSetupConfig = () => setupRemote().allowAppInstance;

Is there any way to mock allowAppInstance to pass the test? I really don't know what to do and what am I doing wrong

Upvotes: 1

Views: 9930

Answers (1)

Nader Alfakesh
Nader Alfakesh

Reputation: 201

You can add the setup property manually with mock function at the top of your test: but depending on how your app uses allowAppInstance you may need to do some extra work.

const setup = {appConfig: jest.fn();}
Object.defineProperty(window, 'setup', setup);

Upvotes: 0

Related Questions