본문 바로가기

Project/TIL

20.03.27 ShareBook TIL

token을 확인하고 유저가 책을 등록하는 함수를 test case로 작성하기

실제 로직이 돌아가는 형태는 유저가 로그인을 하면 토큰이 쿠키에 담겨 보내지며 클라이언트에서 작성된 내용을 request로 보내지고 server에서는 토큰을 verify 해서 유효한 토큰인지를 확인한 뒤 데이터베이스에 담긴다.

test에서는 beforeAll로 먼저 토큰을 생성해준다.

import 'dotenv/config'; // 이걸 불러와서 실제 로직에서 사용하는 .env가 작동함

beforeAll(done => {
    request(app)
      .post('/users/signin')
      .send({
        email: 'test_123@gmail.com',
        password: 'test_password',
      })
      .end((err, response) => {
        token = response.body.token; // save the token!
        // console.log(token);
        done();
      });
  });

 

end()에서 토큰을 받으면 모든 테스트에서 액세스 할 수 있는 변수에 토큰을 저장할 수 있다.

 

describe('POST /books/registerBook', () => {
    test('should respond book info to registerBook data', async done => {
      const response = await request(app)
        .post('/books/registerBook')
        .set('Cookie', `data=${token}`)
        .send({
          name: 'test_book',
          publisher: 'test_pub',
          writer: 'test_writer',
          quelity: 'test_quelity',
          description: 'test_desc',
          image: 'test_image',
          isRental: '대여 가능',
          bookRegion: 'test_서울 관악구 봉천동',
          userOwnerId: 1,
        });
      expect(response.status).toEqual(200);
      done();
    });
  });

 

※참고 레퍼런스

https://blog.stvmlbrn.com/2018/06/18/test-jwt-authenticated-express-routes-with-jest-and-supertest.html

 

Test JWT-Authenticated Express Routes with Jest And SuperTest

So you have decided to use JSON Web Tokens (JWT) to secure your API, or you are already using JWT and need to add some unit tests for your routes, and you are a little unsure how to acquire, store, and pass the required token to complete the test. Let’s ta

blog.stvmlbrn.com

 

'Project > TIL' 카테고리의 다른 글

20.03.29 ShareBook TIL  (0) 2020.03.29
20.03.28 ShareBook TIL  (0) 2020.03.29
20.03.26 ShareBook TIL  (0) 2020.03.26
20.03.25 ShareBook TIL  (0) 2020.03.25
20.03.24 ShareBook TIL  (0) 2020.03.25