Skip to content

Instantly share code, notes, and snippets.

@dennisja
Created November 18, 2018 18:53
Show Gist options
  • Save dennisja/e3264061839f39fbcb80bc7b9ca32544 to your computer and use it in GitHub Desktop.
Save dennisja/e3264061839f39fbcb80bc7b9ca32544 to your computer and use it in GitHub Desktop.
import React from "react";
// get the MockedProvider from react-apollo/test-utils
import { MockedProvider } from "react-apollo/test-utils";
import { cleanup, render } from "react-testing-library";
import UsersList, { GET_USERS_QUERY } from "./UserList";
describe("UserList component", () => {
afterEach(cleanup);
const request = {
query: GET_USERS_QUERY
};
const result = {
data: {
users: [
{
id: "2",
firstName: "john",
lastName: "doe",
email: "[email protected]",
username: "jd"
},
{
id: "4",
firstName: "jack",
lastName: "happer",
email: "[email protected]",
username: "jh"
}
]
}
};
it("should render the users list", async () => {
const { getByText } = render(
<MockedProvider mocks={[{ request, result }]} addTypename={false}>
<UsersList />
</MockedProvider>
);
// wait for the request to come back
await new Promise(resolve => setTimeout(resolve));
// loop through all users to check that they are rendered
result.data.users.forEach(user => {
// find a row which has firstName and lastName of each person
const firstNameHolder = getByText(
new RegExp(`${user.firstName} ${user.lastName}`, "ig")
);
// since these are dom nodes, we can find the next sibling which contains an email
const emailHolder = firstNameHolder.nextElementSibling;
// look for the username holder as well
const userNameHolder = emailHolder.nextElementSibling;
// ensure email holder has email
expect(emailHolder.textContent).toBe(`Email: ${user.email}`);
// ensure username holder has username
expect(userNameHolder.textContent).toContain(user.username);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment