wam
w__am 개발노트
wam
  • 분류 전체보기 (165)
    • CS 지식 (10)
      • 자료구조 (0)
      • 알고리즘 (0)
      • 컴퓨터 구조 (0)
      • 운영체제 (0)
      • 네트워크 (7)
      • 데이터베이스 (0)
      • 디자인 패턴 (3)
    • Frontend (131)
      • Three.js (64)
      • NPM (1)
      • Nest.js (19)
      • React (10)
      • Apollo (7)
      • TypeScript (2)
      • JavaScript (12)
      • HTML, CSS (1)
      • Jest (3)
      • E2E (5)
      • Cypress (7)
    • Database (12)
      • TypeORM (12)
    • IT 지식 (8)
      • 클라우드 서비스 (3)
      • 네트워크 (1)
      • 데이터 포맷 (2)
      • 기타 (2)
    • IT Book (2)
    • 유용한 사이트 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 🐱 Github

인기 글

태그

  • 렌더링 성능 최적화
  • 함수의 범위
  • type-graphql
  • gridhelper
  • getdelta()
  • mapped types
  • 원형적인 움직임
  • 디자인 패턴
  • 스코프
  • three.js 구성 요소
  • Decorators
  • 함수 선언문
  • axeshelper
  • joi 에러
  • 오프-프레미스(off-premise) 방식
  • math.cos()
  • 함수 리터럴
  • API
  • reactive variables
  • 함수 표현식
  • react 성능 최적화
  • getelapsedtime()
  • 데이터 포맷
  • 초기 환경설정
  • isabstract
  • Interface
  • e.preventdefault()
  • math.sin()
  • 삼각함수
  • threejs 개발 할 때 도움을 줄 수 있는 유틸리티

최근 글

관리자

글쓰기 / 스킨편집 / 관리자페이지
hELLO · Designed By 정상우.
wam

w__am 개발노트

Resolver 테스트 사용법 예제
Frontend/E2E

Resolver 테스트 사용법 예제

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())

 

 

저작자표시 변경금지 (새창열림)

'Frontend > E2E' 카테고리의 다른 글

[초기설정] 테스트가 끝난 후 데이터베이스 내용 drop하기  (0) 2024.07.15
[초기설정] E2E 설정 구성, 경로 변경하기  (0) 2024.07.15
[초기설정] E2E 테스트를 설정하는 예제 코드 설명  (0) 2024.07.15
E2E (End-to-End)  (0) 2024.07.15
    'Frontend/E2E' 카테고리의 다른 글
    • [초기설정] 테스트가 끝난 후 데이터베이스 내용 drop하기
    • [초기설정] E2E 설정 구성, 경로 변경하기
    • [초기설정] E2E 테스트를 설정하는 예제 코드 설명
    • E2E (End-to-End)
    wam
    wam

    티스토리툴바