Why does the `render(...)` result change after the first `it` it callback?

146 views Asked by At

The problem

I am confused why renderResult has a different value in the second it callback

describe(`Time picker`, () => {
  const renderResult = renderTestForm(mockData);
  it.only('starts at 6:00 PM', () => {
    expect(renderResult.asFragment()).toMatchInlineSnapshot(
      `<DocumentFragment>
         <div class="css-view-1dbjc4n">
            ...I won't  include it all...
         </div>
      </DocumentFragment>`)
    const timeInput = within(renderResult.getByTestId('time_input'));
    const options = timeInput.getAllByTestId('option');
    expect(options[0]).toHaveTextContent('6:00 PM');
  });

  it.only('ends at 5:55 PM', () => {
    expect(renderResult.asFragment()).toMatchInlineSnapshot(
      `<DocumentFragment />` // EMPTY... why??
    );
    // ERROR Unable to find an element by:
    // const timeInput = within(renderResult.getByTestId('time_input'));
    //                                      ^|        
    const timeInput = within(renderResult.getByTestId('time_input'));
    const options = timeInput.getAllByTestId('option');
    expect(last(options)).toHaveTextContent('5:55 PM');
  });
});

The solution

To fix, I do this:

diff of fix

The fix looks good to me, but I find it surprising it works. I'm missing/forgetting something to do with jest or react-testing library.

Question

What is happening between the first and second it to mutate renderResult?

Not question

I am not asking for alternative solutions, my solution works fine but I don't understand why it works. So "why does this work" is my question

Thanks

Note

renderTestForm is a utility renders a form with some providers and calls render with some wrapped. The form has a heap of async operations, and there is a bunch of jest async, so perhaps this is the culprit. But even so, I always thought of it as a abstraction for "work", not for "renders" or "time" so I'm surprised at the different behavior within subsequent it callbacks.

import { render } from '@testing-library/react';
jest.mock('...many things..');
const renderTestForm = (data) => render(
  <SomeProviders>
     <MyForm data={data}/>
  </SomeProviders>
)
0

There are 0 answers