beforeEach(() => {
jest.spyOn(console, 'error').mockImplementation()
jest.spyOn(console, 'info').mockImplementation()
})
test에서 console 출력하지 않게 하기
출력을 확인하고 싶다면
const spyConsole = jest.spyOn(console, 'error').mockImplementation()
const consoleOutput = spyConsole.mock.lastCall?.[0]
같은 식으로 확인한다.
jest.mock('moment', () => () => jest.requireActual('moment')('11.02.2022 10:10', 'DD.MM.YYYY HH:mm'))
moment() mocking 하기
https://elnathsoft.pl/mocking-moment-with-jest/
에서 얻었으며, 원리는 moment() 를 mocking하는데, mocking되지 않는 진짜 moment를 사용하는 것이었다.
producerObj
.on('ready', () => resolve(producerObj))
kafka 프로듀서는 on 으로 이벤트를 처리한다. (EventEmitter 상속)
emit을 해야 하는데, EventEmitter 는 자기가 emit 한 것만 on으로 받는다.
그로인해 이건 목을 할 수 없다.
const spyProduce = jest
.spyOn(Producer.prototype, 'produce')
.mockImplementationOnce(() => {
throw new Error('Local: Queue full')
})
.mockImplementationOnce(() => {
throw new Error('something wrong')
})
.mockImplementation()
위와 같이 mockImplementation을 변경할 경우
//throw new Error('Local: Queue full')
expect(spyProduce).toBeCalledTimes(1) // actual 2
//throw new Error('something wrong')
expect(spyProduce).toBeCalledTimes(1) // actual 2
// nothing
expect(spyProduce).toBeCalledTimes(1) // actual 3
calledTimes 는 초기화 된다.
this를 사용하는 Mock 하고 싶었는데 안되더라.
const mockFetch = fetch as jest.MockedFunction<typeof fetch>
mockFetch.mockResolvedValue({ ok: true, text: failText } as unknown as Response)
왜인지 메모를 안 해놨는데, node-fetch 를 쓰고 있는 현재 프로젝트에서 fetch는 spyOn으로 mocking이 되지 않았다.