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!