728x90
반응형

DELETE와 PATCH도 추가해보자.

DELETE를 먼저 테스트 수행하면 남아있는 데이터가 없기 때문에 PATCH부터 작성한다.

 

  describe('/movies/:id',() => {
    it('GET 200', () => {
      return request(app.getHttpServer())
        .get('/movies/1')
        .expect(200)
    });
    it('GET 404', () => {
      return request(app.getHttpServer())
        .get('/movies/999')
        .expect(404)
    });
    it('PATCH 200', () => {
      return request(app.getHttpServer())
        .patch('/movies/1')
        .send({ title : 'Updated Test'})
        .expect(200)
    });
    it('DELETE 200', () => {
      return request(app.getHttpServer())
        .delete('/movies/1')
        .expect(200);
    });
  });

 

테스트를 수행해보면

 

정상으로 작동했다.

 

이번에는 잘못된 데이터를 가진 movie를 create하는지 테스트해보자.

  describe('/movies', () => {
    it('GET',() => {
      return request(app.getHttpServer())
        .get('/movies')
        .expect(200)
        .expect([]);
    });

    it('POST 201',() => {
      return request(app.getHttpServer())
        .post('/movies')
        .send({
          title: 'Test Movie',
          genres: ['test'],
          year: 2000
        })
        .expect(201)
    });

    it('POST 400',() => {
      return request(app.getHttpServer())
        .post('/movies')
        .send({
          title: 'Test Movie',
          genres: ['test'],
          year: 2000,
          other: "thing"
        })
        .expect(400)
    });

    it('DELETE', () => {
      return request(app.getHttpServer())
        .delete('/movies')
        .expect(404)
    });
  });

 

테스트를 수행해보면

 

 

정상적으로 작동하였다.

728x90
반응형
728x90
반응형

 

우리가 테스트를 진행하는 동안에 테스트를 마치고 다른 테스트를 진행할 때 항상 만들어 두었던 데이터베이스가

사라졌었다.( 새로운 테스트 진행마다 앱이 새로 생성됨 ) 이 과정이 귀찮으면 beforeAll Hook을 추가할 수 있다.

 

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

 

이 부분의 beforeEach를 beforeAll로 바꿔준다. 그다음 GET 메서드에서 id로 getOne함수를 사용하는 부분을 추가하자.

 

import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';

describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('this is home');
  });

  describe('/movies', () => {
    it('GET',() => {
      return request(app.getHttpServer())
        .get('/movies')
        .expect(200)
        .expect([]);
    });

    it('POST',() => {
      return request(app.getHttpServer())
        .post('/movies')
        .send({
          title: 'Test Movie',
          genres: ['test'],
          year: 2000
        })
        .expect(201)
    });

    it('DELETE', () => {
      return request(app.getHttpServer())
        .delete('/movies')
        .expect(404)
    });
  });

  describe('/movies/:id',() => {
    it('GET 200', () => {
      return request(app.getHttpServer())
        .get('/movies/1')
        .expect(200)
    })
  })

});

 

/movies/:id에 200 status를 받게끔 코딩하고 테스트를 진행해보면

 

이렇게 에러가 뜨는 것을 확인할 수 있다. 왜 그럴까?

 

실제 서버에서 돌아갈 때는 id가 number라고  뜬다(main.ts에서 transform을 써서 number로 받아옴)

하지만 테스팅 서버에서는 

어떤 pipe에도 올리지 않았다.

 

main.ts에서 적용했던 것처럼 테스팅서버에서도 적용하고 실행해보자.

 

 

아주 잘 작동하는것을 확인할 수 있다.

728x90
반응형
728x90
반응형

유닛 테스트를 좋아하는 사람들이 있는 반면에 e2e 테스트를 좋아하는 사람들도 있다.

e2e테스트는 유닛 테스트할 때처럼 하나하나 테스트하지 않는다.

 

 

먼저 Nest 앱을 만들 때 자동으로 만들어진 이 파일들 부터 보면

 

app.e2e-spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';

describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('Hello World!');
  });
});

 

 

여기서 유닛테스트를 할 때와는 다르게 it함수 안 쪽에 '/'에 GET method로 들어오는 요청들에 대해 테스트를 한 다는것을 볼 수 있다. 이는 Controller, Service, Pipe의 결과에 대해 모든 테스트를 하고 있다는 뜻이기도 하다.

 

일단 먼저 e2e테스트를 실행해보자.

$ npm run test:e2e

 

 

 

실패다. 자세히 읽어보면

이 부분에서 우리가 루트 경로에 지정했던 문자열과 테스트할 때의 문자열이 다른것을 확인 할 수 있다.

 

app.controller.ts

import { Controller, Get } from '@nestjs/common';

@Controller('')
export class AppController {
    @Get()
    home() {
        return 'this is home'
    }
}

 

때문에 "Hello World!" 였던 부분을 "this is home"으로 바꿔서 다시 실행해보자.

 

app.e2e-spec.ts

it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('this is home');
  });

 

테스트를 실행해보자.

 

'/' GET 으로 'this is home' 이라는 반환 값을 성공적으로 받았다.

 

이번엔 movies에서 코드를 추가하고 적용해보자

  it('/movies (GET)',() => {
    return request(app.getHttpServer())
      .get('/movies')
      .expect(200)
      .expect([]);
  })

 

테스트를 해보면

 

 

정상적으로 테스트가 진행되었다.

유닛테스트를 할 때 처럼 좀 더 깔끔하게 다듬어서 POST까지 테스트해보자.

 

app.e2e-spec.ts

  describe('/movies', () => {
    it('GET',() => {
      return request(app.getHttpServer())
        .get('/movies')
        .expect(200)
        .expect([]);
    });

    it('POST',() => {
      return request(app.getHttpServer())
        .post('/movies')
        .send({
          title: 'Test Movie',
          genres: ['test'],
          year: 2000
        })
        .expect(201)
    });
  });

 

테스트를 해보면

성공하였다. 이번엔 DELETE까지 추가해보자.

    it('DELETE', () => {
      return  request(app.getHttpServer())
        .delete('/movies')
        .expect(404)
    });

 

 

이렇게 GET, POST, DELETE 메소드 별로 테스트를 해보았다.

728x90
반응형

+ Recent posts