@testing-library/react#act TypeScript Examples

The following examples show how to use @testing-library/react#act. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: test-utils.tsx    From abacus with GNU General Public License v2.0 7 votes vote down vote up
/**
 * Change the value in a form field.
 */
export async function changeFieldByRole(role: string, name: RegExp, value: string) {
  const field = screen.getByRole(role, { name: name })
  // eslint-disable-next-line @typescript-eslint/require-await
  await act(async () => {
    fireEvent.change(field, { target: { value: value } })
  })
}
Example #2
Source File: util.test.tsx    From backstage with Apache License 2.0 7 votes vote down vote up
describe('util', () => {
  describe('useNavigateToQuery', () => {
    it('navigates to query', async () => {
      const MyComponent = () => {
        const navigateToQuery = useNavigateToQuery();
        navigateToQuery({ query: 'test' });
        return <div>test</div>;
      };

      await act(async () => {
        await render(
          wrapInTestApp(
            <Routes>
              <Route element={<MyComponent />} />
            </Routes>,
            {
              mountedRoutes: {
                '/search': rootRouteRef,
              },
            },
          ),
        );

        expect(navigate).toHaveBeenCalledTimes(1);
        expect(navigate).toHaveBeenCalledWith('/search?query=test');
      });
    });
  });
});
Example #3
Source File: useDebounce.test.tsx    From one-platform with MIT License 6 votes vote down vote up
test('update after timeout', async () => {
  // inital state
  const { rerender } = render(<UseDebounceTest />);
  let textEl = screen.getByText(/hello/i);
  expect(textEl).toBeInTheDocument();
  act(() => {
    // prop change
    rerender(<UseDebounceTest text="hello world" />);
  });
  // should not immediately change
  textEl = screen.getByText(/hello/i);
  expect(textEl).toBeInTheDocument();

  act(() => {
    jest.runAllTimers();
  });
  // should be changed
  textEl = screen.getByText(/hello world/i);
  expect(textEl).toBeInTheDocument();
});
Example #4
Source File: App.test.tsx    From react-doc-viewer with Apache License 2.0 6 votes vote down vote up
test("renders component with no file name", async () => {
  let comp = render(
    <DocViewer
      documents={[{ uri: require("../_example-files_/pdf.pdf") }]}
      config={{ header: { disableFileName: true } }}
    />
  );

  act(async () => {
    await comp?.findByTestId("file-name");
  });

  expect(comp?.getByTestId("react-doc-viewer")).toMatchSnapshot();
});
Example #5
Source File: ExperimentPageView.test.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
renderExperimentPageView = async ({ experiment: experimentOverrides = {} }, view: ExperimentView) => {
  const experiment = Fixtures.createExperimentFull(experimentOverrides)
  mockedExperimentsApi.findById.mockImplementationOnce(async () => experiment)

  const metrics = Fixtures.createMetrics(10)
  mockedMetricsApi.findAll.mockImplementationOnce(async () => metrics)

  const segments = Fixtures.createSegments(10)
  mockedSegmentsApi.findAll.mockImplementationOnce(async () => segments)

  const analyses = Fixtures.createAnalyses()
  mockedAnalysesApi.findByExperimentId.mockImplementationOnce(async () => analyses)

  const tags = Fixtures.createTagBares(5)
  mockedTagsApi.findAll.mockImplementationOnce(async () => tags)

  const debug = view === ExperimentView.Debug

  // This `act` is needed to fix warnings:
  await act(async () => {
    render(<ExperimentPageView experimentId={experiment.experimentId} view={view} debugMode={debug} />)
  })
}
Example #6
Source File: LoginPage.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('Login page', () => {

    it("logs in, fetches user data", async () => {
        render(<LoginPage />);

        const loginBtn = await screen.findByText('Login');

        const emailInput = document.getElementById('email-input');
        expect(emailInput).toBeTruthy();
        const passwordInput = document.getElementById('password-input');
        expect(passwordInput).toBeTruthy();

        fireEvent.change(emailInput, { target: { value: '[email protected]' } });
        fireEvent.change(passwordInput, { target: { value: 'passs' } });
        fireEvent.click(loginBtn);

        await act(async () => {
            const userInfo = getStoreItem('userInfo');
            expect(userInfo.fullName).toEqual(testData.fullName);
        });
    });
});
Example #7
Source File: AddRows.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Resets on blur when value is invalid', () => {
  render(<AddRows addRows={() => null} />)
  const input = screen.getByRole('spinbutton') as HTMLInputElement
  // Force the input to be of type "text" to test what happens if the user types in non-number characters
  input.type = 'text'

  act(() => {
    userEvent.type(input, '{selectall}{backspace}')
    input.blur()
  })
  expect(input.value).toBe('1')

  act(() => {
    userEvent.type(input, '{selectall}456xyz')
    input.blur()
  })
  expect(input.value).toBe('456')

  act(() => {
    userEvent.type(input, '{selectall}abc')
    input.blur()
  })
  expect(input.value).toBe('1')
})
Example #8
Source File: testUtils.tsx    From crowdsource-dataplatform with MIT License 6 votes vote down vote up
verifyAxeTest = (params: VerifyAxeTestParams) => {
  it('should not fail an axe audit', async () => {
    let axeResult;

    await act(async () => {
      axeResult = await axe(typeof params === 'function' ? params().container : params.container);
    });

    expect(axeResult).toHaveNoViolations();
  });
}
Example #9
Source File: CrystalBall.test.tsx    From ds2020_mauricio with GNU General Public License v3.0 6 votes vote down vote up
test("renders CrystalBall", () => {
  let linkElement: any = null;

  act(() => {
    const { getByText } = render(<CrystalBall />);
    linkElement = getByText(/What is your future/i);
  });

  expect(linkElement).toBeInTheDocument();
});
Example #10
Source File: SelectField.tsx    From uniforms-patternfly with Apache License 2.0 6 votes vote down vote up
test('<SelectField> - renders a select which correctly reacts on change', () => {
  const onChange = jest.fn();
  const element = <SelectField name="x" />;
  const wrapper = mount(
    element,
    createContext(
      { x: { type: String, allowedValues: ['a', 'b'] } },
      { onChange },
    ),
  );

  act(() => {
    const changeEvent = wrapper.find(Select).prop('onSelect')('event', 'b');
    expect(changeEvent).toBeFalsy();
  })

  expect(wrapper.find(Select)).toHaveLength(1);
  expect(onChange).toHaveBeenLastCalledWith('x', 'b');
});
Example #11
Source File: App.test.tsx    From ts-redux-react-realworld-example-app with MIT License 6 votes vote down vote up
it('Should render home', async () => {
  act(() => {
    store.dispatch(initializeApp());
  });
  mockedGetArticles.mockResolvedValueOnce({
    articles: [],
    articlesCount: 0,
  });
  mockedGetTags.mockResolvedValueOnce({ tags: [] });
  mockedGetUser.mockImplementationOnce(jest.fn());
  localStorage.clear();

  await act(async () => {
    await render(<App />);
  });

  expect(screen.getByText('A place to share your knowledge.')).toBeInTheDocument();
  expect(mockedGetUser.mock.calls.length).toBe(0);
  mockedGetUser.mockClear();
});