jest 테스트

마가·2022년 11월 2일

daily

목록 보기
6/7

하루종일 테스트를 짜다.

  1. 모듈에서 특정 함수를 모킹할 때
 jest.spyOn(모듈명, '함수명').mockImplementation(mock함수)

목이 필요한 일의 대부분은 spyOn을 사용한다.

static class를 모킹하는 법에 대해서 아래와 같이 하는데, 그러면 좋지 않다.

// code to mock
export class AnalyticsUtil {
    static trackEvent(name) {
        console.log(name)
    }
}

// mock
jest.mock('../src/AnalyticsUtil', () => ({
    AnalyticsUtil: {
        trackEvent: jest.fn()
    }
}))

https://stackoverflow.com/questions/50421732/mocking-up-static-methods-in-jest

이렇게 하면 아래 말할 restore가 안되어서 다른 테스트에 영향을 주더라.
한가지 mock으로 모든 테스트가 공유한다면 몰?루

  1. mock 복원

아래 링크 참조
https://haeguri.github.io/2020/12/21/clean-up-jest-mock/
beforeEach에 추가하거나 TC 끝에 restore 하는 것도 좋으나
모두가 지킬거란 보장이 없으니 설정에다가 "restoreMocks": true 를 추가한다.
위치는 jest.config.js 도 좋고 package.jsonjest 를 추가해서 해도 좋고.

  1. 테스트
      expect(failed).toBeUndefined()
      expect(targets).toBeDefined()
      expect(targets.length).toBe(2)
      expect(targets[0]).toStrictEqual(target0)
      expect(e).toBeInstanceOf(Error)
      expect((e as Error).message).toBe('~~')

이런 함수들이 있다.
toStrictEqual 덕에 spring에서 JUnit 으로 테스트할 때 보다는 편하다.

        .andExpect(status().is(200))
        .andExpect(jsonPath("$[0].key").value(1))
        .andExpect(jsonPath("$[0].price").value(1.0))
        .andExpect(jsonPath("$[0].wholesale").value(1.0))
        .andExpect(jsonPath("$[0].deliveryFee").value(1.0))
        .andExpect(jsonPath("$[0].etcFee").value(1.0))
        .andExpect(jsonPath("$[0].adFee").value(1.0))
        .andExpect(jsonPath("$[0].pakFee").value(1.0))
        .andExpect(jsonPath("$[0].marketFee").value(1.0))
        .andExpect(jsonPath("$[0].storageFee").value(1.0))
        .andExpect(jsonPath("$[0].createTime").exists())
        .andExpect(jsonPath("$[0].expectSales").value(1.0))
        .andExpect(jsonPath("$[0].profit").exists())
        .andExpect(jsonPath("$[0].profitPercent").exists())
        .andExpect(jsonPath("$[0].purchaseCnt").value(1.0))
        .andExpect(jsonPath("$[0].title").value("title"))

구아악...

profile
마음 가는 길은 죽 곧은 길

0개의 댓글