I am writing unit tests for my React JS application using Jest and React testing library. I am trying to test the async functions. But it is not working.
This is my test
import React from 'react';
import "regenerator-runtime/runtime"
import {render, waitFor, fireEvent, screen} from '@testing-library/react';
import {DonorSelect} from "../../src/components";
import MockAdapter from "axios-mock-adapter";
import Axios from 'axios';
import vars from "../configVars";
import {searchUsersResponse} from "../mock/apiResponse";
import { act } from "react-dom/test-utils"
test ("DonorSelect Component", async () => {
let selectedUser = null;
let users = [ ];
let inputValue=""
//mock the users api endpoint
let mock = new MockAdapter(Axios);
mock.onGet(`${vars.baseApEndpoint}/users?keyword=client`)
.reply(200, searchUsersResponse)
await act(async() => await render(
<DonorSelect
id={"user_select"}
onSelect={(user, displayText) => {
selectedUser = { ...user }
}}
onInputChange={(textFieldValue) => {
inputValue = textFieldValue;
}}
onUsersFetched={(userItems) => {
users = [ ...userItems ]
}}
onChange={(name, value) => {
}}
label={"Search User"}
placeholder={"Please, select a user."}
name={"user"}
value={selectedUser!=null? selectedUser.id:""}
inputValue={inputValue}
/>
))
//assert that input is rendered
expect(screen.getByTestId("user_select_input")).toBeTruthy()
fireEvent.change(screen.getByTestId("user_select_input"), {
target: { value: "client" }
})
fireEvent.focus(screen.getByTestId("user_select_input"))
await waitFor(() => {
//assert that if the label is rendered
expect(screen.getByTestId("user_select_label")).toBeTruthy()
// assert that input is rendered
expect(screen.getByTestId("user_select_user_item_0")).toBeTruthy()
})
})
As you can see in the test what is not working is the last expect()
expect(screen.getByTestId("user_select_user_item_0")).toBeTruthy()
It is always failing. What that component is doing is that, when the input value changes and focus on the input, it will make the api request and render the items. The component is working as expected. I have fully tested it. But it is just not working in the test. What is wrong with my code and how can I fix it?
(props.inputValue =="" || users.length< 1)
. It can be seen that you provided inputValue in tests. But it looks like users is empty. You should have been test foruser-autocomplete-users-wrapper
to make the test more specific. – Estus Flask