Build basic <Avatar /> component with TDD
Build a basic <Avatar /> component using test-driven-development.
Inside the /src directory, create a new file called Avatar.test.tsx and add the following:
import { describe, expect, it } from "vitest";
import { render, screen } from "@testing-library/react";
import Avatar from "./Avatar";
describe("Avatar", () => {
it("should render an img with alt text", () => {
render(<Avatar />);
const img = screen.getByAltText("@github-handle")
expect(img).toBeInTheDocument();
expect(img.tagName).toBe("IMG");
});
});
Now inside your terminal, run yarn test
Ah, it can’t run because we haven’t defined Avatar.
Inside /src create Avatar.tsx and add the following:
function Avatar() {
return <div />
}
export default Avatar
After saving, our test will re-run and fail. Good. Seeing the logs, it shows the rendered component which doesn’t look like.
Let’s fix it. Change Avatar.tsx to this:
function Avatar() {
return <img src="https://cataas.com/cat/says/hello%20world!" alt="@github-handle"/>
}
export default Avatar
And now it passes! Great.
Resources
The following resources provide more information for this lesson:
- TDD Community of Practice
- When I follow TDD
- MDN Docs: Element.tagName
- Testing Library: ByAltText
- Cat as a service
Transcript
Inside the source directory create a new file called Avatar.test.tsx and paste this in. Here, our test is checking that we're rendering an image with alt text, so we're grabbing the image by the alt test. We're also double-checking that it is indeed, an image.
Now, in the terminal run yarn test, and you'll see it's failing to load Avatar. That's because we haven't created it. Let's go ahead and do that. Inside our source create Avatar.tsx and add the bare minimum to get this working.
If we save again, we'll save inside of our test. It'll run again and it runs but fails, because there's nothing being rendered. Now, change it to return an image for our source. We're going to use a cap photo, and alt use at GitHub-handle. Close it, and save. Now, we need to go back to the end and you'll see that it's passing...