Can test files be placed under the pages directory in a Next.js project?

Currently, I am in the process of writing integration tests for the API routes within a Next.js application. One question that has arisen is whether it would be problematic to place the index.test.ts file under the /pages directory. My preference leans towards keeping the test file as close to its associated code file as possible, rather than having to organize it within a separate __test__ directory.

./pages/api/path/index.ts

handler.get(async (req: NextApiRequest, res: NextApiResponse) => {
  ...
});

export default handler;

./pages/api/path/index.test.ts

import { testClient } from "__test__/utils/testClient";

describe("Testing API POST: /api", () => {
  test("Should return 401 when not authenticated", async () => {
    const request = testClient({ handler });
    const res = await request.post("/api/applications");
    expect(res.status).toEqual(401);
  });
});

Answer №1

Summary: While not initially supported, it is possible to organize test files within the pages directory by adjusting the pageExtensions setting in the next.config.js file.


By default, Next.js considers any file ending with tsx, ts, jsx, or js in the pages directory for page and API route creation and routing.

According to the Custom Page Extensions documentation:

Next.js assumes every tsx/ts/jsx/js file in the pages directory is a page or API route, which can lead to unintended routes being exposed to security risks like denial of service attacks or errors during production bundling

If you add a file called index.test.ts in the pages directory (or any subdirectory), it will be treated as an actual page, potentially causing build errors.

To address this issue, you can customize the expected extensions in Next.js using the pageExtensions property in next.config.js.

module.exports = {
    // Default value is ['tsx', 'ts', 'jsx', 'js']
    pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js']
}

With this modification, only pages with specified extensions will be considered. This allows for organizing test files within the pages directory. For example:

pages/
├─ api/
│   ├─ path.page.ts
│   └─ path.test.ts
├─ _app.page.ts
├─ _document.page.ts
├─ index.page.ts
└─ index.test.ts

In this structure, both path.test.ts and index.test.ts would be excluded from consideration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Turn off caching for a @vercel/postgres query in NextJS by utilizing the application router

The content of my app/page.tsx file is as follows: import AddTodo from "./components/add-todo"; import Todo from "./components/todo"; import { sql } from "@vercel/postgres"; export default async function Home() { let data = ...

I am having issues with Padding, Margin, and default color not functioning properly in tailwind CSS when used with

I am currently working on a next.js 13 project with an app directory and tailwind + daisy UI configuration. Despite this setup, I am experiencing issues with padding, margin, and colors. const ContactUs = () => { return ( <> <div cl ...

Download a file on button click using JavaScript with data extracted from the DOM

I am looking to create a download feature where a user can click a button on the webpage, triggering a JavaScript method to capture the contents of a DOM element and prompt the user for a download. After successfully capturing the DOM element in a JavaScr ...

The OnChange event seems to be malfunctioning as it is not being triggered despite other parts of the code functioning properly

Check out the code snippet below: import React, { useState } from "react"; function IP() { const [ipAddress, setIPAddress] = useState(""); const handleInputChange = (event) => { const inputValue = event.target.value; // ...

A malfunction report stemming from an HTTP error code while using react.js/javascript

In my react.js application, I have a Component that displays an error code. It currently looks like this: https://i.stack.imgur.com/2usiy.png Now, in addition to displaying just the code, I also want to show the reason for the error. Similar to how this ...

Omit a certain td element from the querySelectorAll results

Greetings! I am currently working with an HTML table and I need to figure out how to exclude a specific td element from it, but I'm not sure how to go about it. Here's the HTML code: <table id="datatable-responsive" c ...

Having trouble with state not updating correctly after making a fetch request within a useEffect hook in

In my React app with an Express backend, I am facing a challenge in updating the component state using the useEffect hook to trigger once when the component renders. Inside the useEffect, I fetch data from the Express server. const Favorites = ({ user }) = ...

Displaying Hierarchical Data with AngularJS and ng-repeat

Recently, I've been working on finding an elegant solution to represent hierarchical data in my application. Specifically, I have implemented a slide effect for bootstrap badges that showcase sub-categories using AngularJS. With some guidance from th ...

Creating a step wizard form with ReactJs can be accomplished by breaking down the form into

I have developed a resume generation application with two main components: BasicDetails and EmploymentDetails. To see a working example, click here: https://codesandbox.io/s/next-dynamic-testing-issue-forked-h1nt8 index.js file: <form onSubmit={ha ...

Modifying Div Size with Jquery

I am working on populating the div container with square boxes, but I'm having trouble adjusting the size of my #gridSquare div. Despite trying to change its height and width using jQuery, it doesn't seem to work as expected. $('#gridSquare ...

Secure Flask API used for serving JSON files to a basic HTML, JavaScript, and CSS web application

I have developed a basic web application that will display data in a table and be updated on a weekly basis. To perform this update, I utilize Python code in the backend to scrape and modify data before storing it in a SQLite database. After some researc ...

When trying to implement a dark/light theme, CSS variables may not function properly on the body tag

Currently, I am in the process of developing two themes (light and dark) for my React website. I have defined color variables for each theme in the main CSS file as shown below: #light{ --color-bg: #4e4f50; --color-bg-variant: #746c70; --color-primary: #e2 ...

Creating an alert pop-up that displays text based on the prompt input type: A step-by-step guide

I'm a new to Javascript and I'm trying out some basic scripts. My objective is to display a prompt message (1.) asking for a name, then show an alert (2.) based on the input from the prompt. If the input is a valid name (a string), then the alert ...

How about, "Enhance your website navigation with a sleek anchor

After many attempts to implement smooth scrolling on my Bootstrap project, I have tried numerous Youtube tutorials and Google search results without any success. The latest attempt I made was following this Stack Overflow post Smooth scrolling when clickin ...

I am puzzled as to why my code in React is rendering twice without any apparent reason

I ran into a strange issue where my console.log("hi") was being displayed twice. I was working on a simple todo-list project and noticed that everything was getting double clicked. After some troubleshooting, it seems like the code is executing any JavaScr ...

Utilizing an Array of objects in conjunction with $.when

I have a list of Ajax requests stored in an Array, and I need to wait for all of them to finish loading before processing the results. Here is the code snippet I am currently using: $.when( RequestArray ).done(function(){ this.processResu ...

Node.js routing currently lacks the ability to easily verify the presence of a JWT token for every route

I have a node application where, upon routing to ('/login') with valid credentials, I generate a JWT token with an expiry time and direct the user to the next page. If the user tries to access any other route directly (e.g., '/home') af ...

Mastering div manipulation with jQuery: A step-by-step guide

I have three divs with the classes "col-md-2," "col-md-8," and "col-md-2." What I want is that when a button in the "col-md-8" div is clicked, both of the other divs should be hidden and the "col-md-8" div should expand to occupy the full width of "col-md ...

Select Menu (Code Languages:CSS, JS, HTML, BBCode)

I'm currently in the process of setting up a BB code for a forum I moderate. Here's the code snippet I'm using to generate a dropdown box that users can add to the signature field of their profiles: <!DOCTYPE html> <html> <d ...

What is the best way to securely store a sensitive Stripe key variable in an Angular application?

When implementing Stripe payment system in my Angular App, I often wonder about the security of storing the key directly in the code as shown below. Is this method secure enough or should I consider a more robust approach? var handler = (<any>windo ...