Frontend/E2E

Resolver 테스트 사용법 예제

wam 2024. 7. 15. 19:58

 

공통 코드 빼기

 

 

bestTest

  const baseTest = () => request(app.getHttpServer()).post(GRAPHQL_ENDPOINT);
  • 기본적으로 모든 test의 기본이 되는 것들을 반환한다.

 

 

publicTest

  const publicTest = (query: string) => baseTest().send({ query });
  • publicTest는 query string을 받아서 bestTest의 모든것에 send query를 추가한다.

 

 

privateTest

  const privateTest = (query: string) =>
    baseTest().set("X-JWT", jwtToken).send({ query });
  • privateTest는 bestTest의 모든 것을 받아서
  • token을 set하고
  • string으로 된 query를 받아서 전송한다.

 

 

변수 사용하지 않은 코드

import * as request from "supertest";
...

const GRAPHQL_ENDPOINT = "/graphql";

const TEST_USER = {
  email: "e2e@gmail.com",
  password: "123",
};

describe("UserModule (e2e)", () => {

 ...

  describe("createAccount", () => {
    it("should create account", () => {
      return request(app.getHttpServer())
        .post(GRAPHQL_ENDPOINT)
        .send({
          query: `
          mutation {
            createAccount(input: {
              email:"${TEST_USER.email}",
              password:"${TEST_USER.password}",
              role: Owner
            }) {
              ok
              error
            }
          }
          `,
        })
        .expect(200)
        .expect((res) => {
          const {
            body: {
              data: { createAccount },
            },
          } = res;
          expect(createAccount.ok).toBe(true);
          expect(createAccount.error).toBe(null);
        });
    });
    
  describe("userProfile", () => {
    let userId: number;

    beforeAll(async () => {
      const [user] = await usersRepository.find();
      userId = user.id;
    });

    it("should see a user's profile", () => {
    return (
      request(app.getHttpServer())
        .post(GRAPHQL_ENDPOINT)
        // superTest를 사용해서 header를 set하기
        .set("X-JWT", jwtToken)
        .send({
          query: `
        {
          userProfile(userId: ${userId}) {
            ok
            error
            user {
              id
            }
          }
        }
        `,
        })
        .expect(200)
        .expect((res) => {
          const {
            body: {
              data: {
                userProfile: {
                  ok,
                  error,
                  user: { id },
                },
              },
            },
          } = res;
          expect(ok).toBe(true);
          expect(error).toBe(null);
          expect(id).toBe(userId);
        });
    });
});

 

 

변수를 사용한 코드

import * as request from "supertest";
...

const GRAPHQL_ENDPOINT = "/graphql";

const TEST_USER = {
  email: "e2e@gmail.com",
  password: "123",
};

describe("UserModule (e2e)", () => {

 ...
 
	const baseTest = () => request(app.getHttpServer()).post(GRAPHQL_ENDPOINT);
  const publicTest = (query: string) => baseTest().send({ query });
  const privateTest = (query: string) =>
    baseTest().set("X-JWT", jwtToken).send({ query });
    
  beforeAll(async () => { ...  }).compile();

  describe("createAccount", () => {
    it("should create account", () => {
      return publicTest(`
            mutation {
            createAccount(input: {
              email:"${TEST_USER.email}",
              password:"${TEST_USER.password}",
              role: Owner
            }) {
              ok
              error
            }
          }
          `)
        .expect(200)
        .expect((res) => {
          const {
            body: {
              data: { createAccount },
            },
          } = res;
          expect(createAccount.ok).toBe(true);
          expect(createAccount.error).toBe(null);
        });
    });
    
  describe("userProfile", () => {
    let userId: number;

    beforeAll(async () => {
      const [user] = await usersRepository.find();
      userId = user.id;
    });

    it("should see a user's profile", () => {
      return privateTest(`
          {
            userProfile(userId: ${userId}) {
              ok
              error
              user {
                id
              }
            }
          }
          `)
        .expect(200)
        .expect((res) => {
          const {
            body: {
              data: {
                userProfile: {
                  ok,
                  error,
                  user: { id },
                },
              },
            },
          } = res;
          expect(ok).toBe(true);
          expect(error).toBe(null);
          expect(id).toBe(userId);
        });
    });
});

 

 

변수를 사용한 코드, 리펙토링

import * as request from "supertest";

const GRAPHQL_ENDPOINT = "/graphql";

const TEST_USER = {
  email: "e2e@gmail.com",
  password: "123",
};

describe("UserModule (e2e)", () => {
  let jwtToken: string;
  let userId: number;

  const baseTest = () => request(app.getHttpServer()).post(GRAPHQL_ENDPOINT);
  const publicTest = (query: string) => baseTest().send({ query });
  const privateTest = (query: string) => baseTest().set("X-JWT", jwtToken).send({ query });

  beforeAll(async () => {
    // Your setup code here (e.g., initialize app, get JWT token)
  });

  describe("createAccount", () => {
    const createAccountMutation = `
      mutation {
        createAccount(input: {
          email: "${TEST_USER.email}",
          password: "${TEST_USER.password}",
          role: Owner
        }) {
          ok
          error
        }
      }
    `;

    it("should create account", () => {
      return publicTest(createAccountMutation)
        .expect(200)
        .expect((res) => {
          const { ok, error } = res.body.data.createAccount;
          expect(ok).toBe(true);
          expect(error).toBe(null);
        });
    });
  });

  describe("userProfile", () => {
    beforeAll(async () => {
      const [user] = await usersRepository.find();
      userId = user.id;
    });

    const userProfileQuery = (userId: number) => `
      {
        userProfile(userId: ${userId}) {
          ok
          error
          user {
            id
          }
        }
      }
    `;

    it("should see a user's profile", () => {
      return privateTest(userProfileQuery(userId))
        .expect(200)
        .expect((res) => {
          const { ok, error, user } = res.body.data.userProfile;
          expect(ok).toBe(true);
          expect(error).toBe(null);
          expect(user.id).toBe(userId);
        });
    });
  });
});

 

 

설명

  • 주의 - "${testUser.email}” , (”) 넣어주기
  • supertest를 이용해서 post request 보내기
  • request를 app.getHttpServer()로 보내기
  • ( ` ) 를 사용하지 않으면 엔터를 넣을 수 없다.
  • expect 정의를 보면 status:number와 callback function이 있다.
  • expect는 callback을 받고, callback은 error나 response를 넘겨준다.

  • 참고 : 데이터베이스를 만들고 user를 만들고 다 만든 다음에 유저를 만든 후엔 table은 사라진다. (await dataSource.dropDatabase())