Search code examples
typescriptnext.jsjestjs

testing UI of next.js app using jest without involving getStaticProps


I have a simple Next 14 page router application. and I want to test the UI using jest without involving getStaticProps function by passing props to page. I try to use process.env.NODE_ENV for returning from getStaticProps in testing environment but it looks like that in the getStaticProps the process.env.NODE_ENV never be test even while Execution of npm test, because I get test failed about database, but the code in testing environment should skip that part

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 all code inside the getStaticProps the test passes!


Solution

  • It seems that relying on NODE_ENV for this test is not a good option at all, I even tried to set it manually by creating a jest.setup.ts file and setting NODE_ENV to test and update the jest configuration, but it didn't work.

    I just need to mock the getStaticProps function for that test