Search⌘ K

Solution: Troubleshooting Next.js Components with Jest

Explore how to effectively test Next.js components using Jest. Learn to validate image elements in the ArticleCard component and verify the output of slug creation functions. This lesson equips you with practical troubleshooting skills to enhance component reliability and maintainability in Next.js applications.

In this exercise, your task was to implement the following tests:

  • Check if the image displayed by the ArticleCard is a valid image (not something else).

  • Check when you utilize the composeArticleSlug function with an article's title, it doesn’t return an empty string.

Let’s review the solution for each task.

Testing the ArticleCard component

You can find the solution code for this method here:

JavaScript (JSX)
describe('ArticleCard', () => {
test('Article link should have correct href', () => {
const article = {
id: 'u12w3o0d',
title: 'Healthy summer melon-carrot soup',
body: 'Lorem ipsum dolor sit amet',
author: { id: '93ksj19s', name: 'John Doe' },
image: { url: 'https://images.unsplash.com/photo-1629032355262-d751086c475d', author: 'Karolin Baitinger' },
};
const component = render(<ArticleCard {...article} />);
const link = component.getByRole('link');
const href = `/articles/${composeArticleSlug(article.id, article.title)}`;
console.log(href);
expect(link).toHaveAttribute('href', href);
});
});
...