#How to test Nextjs FE and API together?

1 messages · Page 1 of 1 (latest)

obtuse spearBOT
#

Hi @silk egret. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can use Jest for testing both the frontend and API in a Next.js application. Here's how you can set it up:

  1. Install the necessary testing libraries: You need to install jest, jest-environment-jsdom, @testing-library/react, and @testing-library/jest-dom as dev dependencies. You can do this by running the following command in your terminal:
npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom

Source (https://nextjs.org/docs/pages/building-your-application/optimizing/testing)

  1. Create a Jest configuration file: Create a jest.config.mjs file in your project's root directory and add the necessary configuration. Here's an example:
import nextJest from 'next/jest'
 
const createJestConfig = nextJest({
 dir: './',
})
 
const config = {
 testEnvironment: 'jest-environment-jsdom',
}
 
export default createJestConfig(config)

Source (https://nextjs.org/docs/pages/building-your-application/optimizing/testing)

  1. Write your tests: You can write your tests in the __tests__ folder in your project's root directory. Here's an example of a test for a Next.js page:
import { render, screen } from '@testing-library/react'
import Home from '../pages/index'
import '@testing-library/jest-dom'
 
describe('Home', () => {
 it('renders a heading', () => {
 render(<Home />)
 
 const heading = screen.getByRole('heading', {
 name: /welcome to next\.js!/i,
 })
 
 expect(heading).toBeInTheDocument()
 })
})

Source (https://nextjs.org/docs/pages/building-your-application/optimizing/testing)

For API routes, you can write tests that make requests to those routes and assert the responses. However, the provided extracts do not include specific examples of API route tests.

#
  1. Run your tests: You can run your tests by adding a test script to your package.json file:
{
 "scripts": {
 "test": "jest --watch"
 }
}

Source (https://nextjs.org/docs/pages/building-your-application/optimizing/testing)

Please note that while Jest is a powerful tool for testing JavaScript and React applications, it might not be sufficient for end-to-end testing of Next.js applications, which might involve server-side rendering, routing, and other features. For such cases, you might need to use additional tools like Playwright (https://playwright.dev/).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@silk egret kapa.ai is still learning and improving, please let us know how it did by reacting below