enzymejs / enzyme

JavaScript Testing utilities for React
https://enzymejs.github.io/enzyme/
MIT License
19.96k stars 2.01k forks source link

Function `mount` does not mock proper data #2572

Closed Dregorio1 closed 1 year ago

Dregorio1 commented 1 year ago

I have code:

import { mount } from 'enzyme';
import AsyncSelect from 'react-select/async';
import nock from 'nock';
import MyComponent from '../MyComponent';
const waitForExpect = require('wait-for-expect');  

describe('Foo', () => {
  let renderer;

  beforeAll(() => {
    nock.restore();
    nock.activate();
  });

  afterAll(async (done) => {
    nock.cleanAll();
  });

  beforeEach(() => {
    nock.cleanAll();
    nock('http://localhost:3000')
      .persist()
      .get('/api/name')
      .reply(() => [200, [{ name: 'Roberto' }]]);
    renderer = mount(
      <MyComponent />,
    );
  });
  it('test', async () => {
      await waitForExpect(() => {
          renderer.update();
          // Here AsyncSelect should have data from above mock because of `mount` function
          const selectName = renderer.find(AsyncSelect).filter({ instanceId: 'selectName' });
      selectName.props().onChange({ target: { value: 'Roberto' } });
       });
  });
});

If I understand document correctly mount function should embed data from the mock. But when I run the last line selectName.props().onChange({ target: { value: 'Roberto' } }); it said that has no target value and when I use there length I have got 0. It is something wrong with mount, my code, or nock?

ljharb commented 1 year ago

mount doesn't mock anything, so i'm not sure where you're getting that. Certainly renderer should contain the results of MyComponent.

I don't know what waitForExpect is for either.

Dregorio1 commented 1 year ago

@ljharb waitForExpect is because I wanted to wait on "call" to API. renderer has MyComponent and AsyncSelect but AsyncSelect has no data in it. Somewhere I have read that if I mock result from the function in my MyComponent mount will embed that data.

ljharb commented 1 year ago

The best way to wait on an API call is to mock it and get the actual promise that the component itself is waiting on.

Dregorio1 commented 1 year ago

@ljharb I mocked it in beforeEach. Did you suggest something else? How should I do that? Any snippet will be great.

ljharb commented 1 year ago

I know you did - but that doesn't capture the promise it produces.

I'm afraid I don't have time to figure out a snippet for it. Generally I'd suggest exhausting your testing options with shallow before resorting to mount, if you haven't already done so.