admin管理员组

文章数量:1307220

I have the configuration of a service inside a ponent 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.

I have the configuration of a service inside a ponent 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.

Share Improve this question asked May 29, 2021 at 23:32 CodeGCodeG 4672 gold badges6 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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.

本文标签: javascriptJest errorCannot read property 39get39 of undefinedStack Overflow