본문 바로가기
서버/Jest

nextjs custom express typeorm jest typescript

by eclipse7727 2021. 12. 6.

nextjs 에 커스텀 express를 사용하여 토이 프로젝트를 진행중이다.

jest로 서버 테스트코드를 작성하려는데 설정이 난해했다.

 

jest 공식 홈페이지를 들어가보면 supertest를 쓰라고 권장한다.

 

Testing Web Frameworks · Jest

Jest is a universal testing platform, with the ability to adapt to any JavaScript library or framework. In this section, we'd like to link to community posts and articles about integrating Jest into popular JS libraries.

jestjs.io

 

 

How to test Express.js with Jest and Supertest

I recently changed from Mocha, Chai to Jest. Pretty lovely experiences. It took a while to figure out the right way to test an express route, but when it works, it works like a charm. I share my exper

www.albertgao.xyz

 

 

npm install --save-dev babel-cli babel-preset-env jest supertest superagent

위 주소처럼 설치할거 설치하고 jest를 실행해 봣으나 typeorm이 말썽이다.

 

typeorm을 사용할때 필요한 config값은 

package.json 파일에 --setupFiles dotenv/config 를 추가해주면 env 값을 가져올 수 있다.

--forceExit 은  express 서버가 꺼지지 않는다면 강제종료 한다. 

 

are there side effects of running jest with --detectOpenHandles --forceExit?

I'm using jest for testing, and in a few test scenarios I get the jest message: Jest did not exit one second after the test run has completed. While taking Jest's recommendation to run with --

stackoverflow.com

"test": "jest --setupFiles dotenv/config --forceExit --detectOpenHandles"

 

다만 jest를 실행하면서 

module.exports = {
  type: "mysql",
  host: "localhost",
  port: 3306,
  username: process.env.DATABASE_ID,
  password: process.env.DATABASE_PASSWORD,
  database: process.env.DATABASE_NAME,
  entities: [
    process.env.NODE_ENV === "production"
      ? "dist/typeorm/entity/*{.ts,.js}" :
      (process.env.NODE_ENV === 'test' ? "**/entity/*{.ts,.js}"
        : "server/typeorm/entity/*{.ts,.js}"),
  ],
  migrations: ["server/typeorm/migration/**/*{.ts,.js}"],
  subscribers: ["server/typeorm/subscriber/**/*{.ts,.js}"],
  cli: {
    entitiesDir: "typeorm/entity",
    migrationsDir: "typeorm/migration",
    subscribersDir: "typeorm/subscriber",
  },
};

ormconfig.js 의 entities 값이 문제가 되었다.

해당 값을 아래와 같이 바꿔주면 잘 된다.

entities: ["**/entity/*.ts"],

 

jest는 실행 순서가 정해져있다. 아래는 공식 문서다.

 

Setup and Teardown · Jest

Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.

jestjs.io

 

먼저 jest가 테스트 코드를 실행하기전에 typeorm을 connection 해줘야한다.

beforeEach에 typeorm connection을 해주고

afterEach에 typeorm 해제해주면 된다.

typeorm connection 부분은 따로 함수로 빼서 사용했다.

describe('main Page', () => {
    beforeEach(async () => {
        try {
            await connection.createDatabase()
            const option = {
                type: "mysql",
                host: "localhost",
                port: 3306,
                username: process.env.DATABASE_ID,
                password: process.env.DATABASE_PASSWORD,
                database: "test",
                entities: ["**/entity/*.ts"],
                subscribers: ["src/migration/*.ts"],
                migrations: ["src/migration/*.ts"],
            }
            await connection.create(option);
        } catch (e) {
            console.log(e)
            console.error(e);
        }
    });


    test("login success", async () => {
        const cookies = await login(http);
        console.log(cookies)
        const response = await http.get('/api/user/logout').set('Cookie', cookies);
        expect(response.status).toEqual(302)
        expect(response.headers.location).toContain(
            '/user/login',
        )
    })

    test('GET /api/post/getPosts 201', async () => {
        const response = await http.get('/api/post/getPosts')
        expect(response.status).toEqual(201);

    });
    afterEach((done) => {
        connection.close()
        done()
    })

});
반응형

댓글