Experimenting with the user interface of a next.js application using jest, all without the need for get

I have a straightforward Next 14 page routing application and I am looking to test the UI with jest without involving the getStaticProps function by passing props directly to the page. I attempted to use process.env.NODE_ENV within getStaticProps in the testing environment, but it seems that the process.env.NODE_ENV is never set to test even when running npm test. This results in a test failed related to the database, which should actually be skipped in the testing environment.

index.tsx => about home page

     const Home = (props:dataType) => {
         const data = props.posts;
        if(data.length === 0) return <p style={{textAlign:"center"}}> Loading ...</p>
        return (
            <div className={classes.home}>
                 <h1 className={classes["home--header"]}>Blog Post App</h1>
                 <h3 className={classes["home--header"]}>showing blog posts</h3>
                <div className={classes['home--main']}>
               {data.map(post=>{
                return <BlogCard key={post["_id"].toString()} 
                   id={post["_id"].toString()} title={post.title} text={post.text}  />
             })}
    
          </div>
     </div>
    );
   };
      

   

     export  async function getStaticProps(){
      console.log(process.env.NODE_ENV);
      if(process.env.NODE_ENV=== "test") return;
        const client = await clientPromise;
        const db = client.db("blogpost");
        const postCollection = db.collection("posts");

        const allPosts = await postCollection.find({}).toArray();


       return {
           props:{posts:JSON.parse(JSON.stringify(allPosts))},
           revalidate:60*5

           };

        }

home.test.tsx => home page test

        import { render, screen } from "@testing-library/react";
        import '@testing-library/jest-dom'
        import Home from "@/pages/index";


       describe("Home",(()=>{


           test("testing page uses crroct Env",()=>{
           const test_env = process.env.NODE_ENV;

           expect(test_env).toBe("test");

            // it passes the test

            });

     test("home page has crroct heading", () => {
        render(
          <Home
            posts={[
               { _id: "1", title: "test post", text: "this is a test for Home page" },
              ]}
          />
        );
  
          const heading = screen.getByRole("heading",{name:/blog post app/i});

          expect(heading).toBeInTheDocument();


          const postTitle = screen.getByTestId("postTitle");
  
         expect(postTitle).toBeInTheDocument();
      });
  
     }));



        

When I comment out all the code inside getStaticProps, the tests pass!

Answer №1

It appears that depending on NODE_ENV for this particular test is not the best approach, I even attempted to manually define it by creating a jest.setup.ts file and setting NODE_ENV to test while updating the jest configuration, but unfortunately, it did not yield the desired results.

All I really need to do is effectively simulate the behavior of the getStaticProps function in that specific test case.

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

Is there a shorthand for using += with a string type that may be null?

What is the most efficient method to convert this JavaScript code into Typescript? let a, b; /* @type {string | null} */ a += b; One possible solution is let a: string | null, b: string | null; a = a || '' + b || ''; However, this app ...

What is the process of uploading a file to my Spring Boot-based WebService using an Angular 5 client?

I've put in a lot of effort to solve my issue, but unfortunately, I haven't had any success yet. Currently, I am working with an Angular 5 client and I need to send a file over to my SpringBoot web service so that I can process it on the server ...

Determine if an object in TypeScript generics includes a specific value

I have been working on a method to verify if a value retrieved from the database matches an enum. At first, I aimed to create a generic TypeGuard, but then I thought it would be beneficial to have a function that not only checks the value against the enum ...

Encountered an error in NextJs where multiple children were passed to <Link> component with the same `href` while mapping

Is there an easy way to map through an array of menu items using the NextJs < Link > component? Here's the code I'm currently using: {navigation.map((item) => ( <Link key={item.name} href={item.href} className={classNam ...

Having difficulty sending the [ctrl][p] keys to a page that is not using Angular framework

Working with protractor version 5.1.2, Angular 5, and typescript 2.4.2 When attempting to trigger a 'print' function using the shortcut keys '[ctrl][p]' in protractor on a non-angular page, I encountered an issue. Within my protractor ...

A special function designed to accept and return a specific type as its parameter and return value

I am attempting to develop a function that encapsulates a function with either the type GetStaticProps or GetServerSideProps, and returns a function of the same type wrapping the input function. The goal is for the wrapper to have knowledge of what it is ...

Expo project encountering issues with nested navigation in React-Native

When configuring the header in my app using React Native Stack Navigation and nesting a Drawer Navigation inside of it, I encountered a strange issue. While everything worked fine in the android emulator, opening the app using Expo resulted in nothing but ...

Unexpected token error on an optional property in Visual Studio Code

I encountered a problem with a project I cloned. Below is the code snippet created using this project: https://github.com/enuchi/React-Google-Apps-Script export interface Vehicle { wheels: number; insurance?: string; } export default class Car { whe ...

What is the best way to set up Storybook.js Webpack to support absolute image paths within CSS modules for a Next.js project?

I'm currently setting up Storybook to integrate with Next.js, Ant Design, Less, and TypeScript. In Next.js, images need to be stored in the public/ directory and linked using absolute paths for universal usage within the project. I am facing challenge ...

Tips for structuring TypeScript with MobX in a ReactJS project

I created a MobX store as shown below. I defined the types of actions in store.js import { action, observable } from 'mobx'; export class SignStore { @observable UserInformation: { email: ''; password: ''; ...

New color scheme in Visual Studio Code for JavaScript and TypeScript files within Visual Studio 2017

I am interested in importing or setting a Visual Studio Code color theme for JavaScript and TypeScript files in Visual Studio 2017. Specifically, I would like to customize the color theme for files with extensions: .js, .jsx, .ts, and .tsx. If individual f ...

Unexpected error in React TypeScript: '=' symbol missing. Code error TS1005

Encountering an issue: '=' expected. TS1005 5 | * LICENSE file in the root directory of this source tree. 6 | */ > 7 | import type { NewPlugin, Optionsz, OptionsReceived } from './types'; | ^ ...

Switching from utilizing apollo-server-micro to upgrading to apollo server 4

While it may seem like a simple task, I'm having trouble understanding the documentation for migrating to Apollo Server 4. My current setup involves using Next.js as a framework without Express, and I'm aiming for a serverless architecture. Belo ...

Combining two interconnected projects: A guide to compiling mutual project dependencies

I am encountering difficulties while constructing a project (@red5/middleware) that relies on another project (@red5/router), which in turn depends on the initial project (@red5/middleware). When I execute the following command: rm -rf types && t ...

What is the best way to export an overloaded function in TypeScript?

Trying to figure out how to overload a function in TypeScript so it can determine the type of arg2 based on the value of arg1. Arg1 has a list of known values. Here's a rough example of what I'm attempting: interface CatArgs {legs : number} int ...

Leveraging the spread operator in cases where the value is null

Is there a more elegant solution for handling null values in the spread operator without using if-else statements? In this specific case, I only want to spread assignedStudents if it is not undefined. When attempting to do this without using if-else, I e ...

Can I pass mat-options to my custom mat-select component using ng-content?

I created a custom select component and attempted to utilize ng-content to pass in my options. Here is the code snippet I used: <lib-select [(selected)]="selected" (selectedChange)="onChange($event)"> <mat-option [value]="0">Value 1</ma ...

Struggling to retrieve local JSON file in Angular 5 - facing relentless 404 error

I've scoured every available article and post on this topic, yet I am still unable to pinpoint where I am making a mistake with this seemingly simple task. (Particularly, following this example.) It seems like I am missing something obvious, but after ...

Is it possible to perform unit testing on an onClick function that does not rely on a mouse click event?

My question is related to an onClick function in React const handleOnClick = (e: React.MouseEvent<HTMLButtonElement>) => { if (e) { this.props.log(); } } I'm wondering how I can test using jest and enzyme ...

Storing data retrieved from a GraphQL response into the sessionStorage: A step-by-step guide

I am facing a challenge in saving my GraphQL response in sessionStorage to access it across different parts of the application without making repeated API calls. I am currently using the useQuery hook with a skip property to check if the data is already st ...