<aside> ⌛ Before using Agent, I delivered manually access and refresh token for each test case to be able to authorize the user in the integration test.
</aside>
test("POST /api/worldcup API (createWorldcup) Integration Test Success Case", async () => {
const createWorldcupRequestBodyParams = {
title: worldcupData.title,
content: worldcupData.content,
choices: worldcupData.choices,
};
const response = await supertest(app)
.post(`/api/worldcup`) // API HTTP Method & URL
.set("Authorization", `Bearer ${userData.accessToken}`) // set Access Token to header
.set("refreshtoken", `${userData.refreshToken}`) // set Refresh Token to header
.send(createWorldcupRequestBodyParams); // Request Body
/** POST /api/worldcup API Success Case Logic **/
expect(response.status).toEqual(201);
expect(response.body).toMatchObject({
newWorldcup: {
worldcup_id: worldcupData.worldcup_id,
user_id: userData.user_id,
title: createWorldcupRequestBodyParams.title,
content: createWorldcupRequestBodyParams.content,
choices: createWorldcupRequestBodyParams.choices,
},
});
});
In the Jest Supertest module, the term "agent" refers to an instance of the supertest module that is created to make HTTP requests to your server during testing. The agent acts as a virtual browser, allowing you to send requests and receive responses from your server without actually starting a server or making network connections.
By creating an agent, you can simulate HTTP requests and test your server's response. The agent retains session information such as cookies between requests, allowing you to maintain stateful behavior during testing. It provides a convenient and efficient way to perform integration testing and API testing by making HTTP requests and asserting on the responses.
describe("POST /api/worldcup API (createWorldcup) Integration Test Success Case", () => {
const agent = supertest.agent(app);
agent
.post("/api/auth/signup")
.send({
nickname: "test1",
password: "abcd1234!",
email: "test1@naver.com",
})
.expect(200);
beforeEach(async () => {
await agent
.post("/api/auth/login")
.send({
nickname: "test4231",
password: "abcd1234!",
})
.expect(200);
});
test("Create worldcup post with logged in status", () => {
const createWorldcupRequestBodyParams = {
title: worldcupData.title,
content: worldcupData.content,
choices: worldcupData.choices,
};
// using agent to keep login status
agent
.post("/api/worldcup")
.send(createWorldcupRequestBodyParams )
.expect(201);
});