-
항해 99 5기 TIL_31항해 99 2022. 2. 10. 02:32
▶ Today I Learned
<TDD>
이번엔 또 다른 테스트 코드를 보다 문득 궁금해졌다.
describe('Sensor 요구사항 테스트', () => { beforeEach(() => { jest.useFakeTimers(); }); afterEach(() => { jest.clearAllTimers(); });
beforeEach()? afterEach?
jest의 공식문서를 보면 before Each()는 다음과 같다.
Runs a function before each of the tests in this file runs. If the function returns a promise, Jest waits for that promise to resolve before running the test.
즉, 파일 내 각각의 테스트가 실행되기 전에 해당 함수를 실행한다는 것이며 함수가 프로미스를 반환할 경우 Jest는 그 프로미스가 해결될 때 까지 기다린다는 것이다.
afterEach()는 그 반대라 보면 되겠다.
[jest.advanceTimersByTime()]
jest.advanceTimersByTime(ms 단위 시간)
공식 문서와 아래 블로그를 참조한 결과, 해당 함수를 실행하면 모든 타이머가 지정한 ms만큼 시간이 지나간것 처럼 보이게 해준다.
이 코드를 사용하면 일정 ms(밀리세컨드) 이 후에 실행되어야 하는 콜백 함수들이 실행된 것처럼 가정해주는 것이다.
실제시간 상으로는 동시에 실행되는 것처럼 보인다.
참조:
https://jestjs.io/docs/timer-mocks
[setTimeout()]
새롭게 다루게 된 IoT 센서 관련 테스트 코드 중
index.spec.js 테스트 코드
test('유휴 상태에서 설정된 reportingInterval 값(단위: ms) 만큼 기다린 후 거리 측정을 한다.', () => { const sensor = new Sensor('id1'); sensor.turn('on'); expect(sensor.status).toEqual('idle'); jest.advanceTimersByTime(sensor.reportingInterval); // 유휴 대기 시간 // 테스트코드에서 타이머에 설정된 시간을 이미 지난것 처럼 해주자. // jest.useFakeTimers();랑 jest.advanceTimersByTime(sensor.reportingInterval);를 같이 쓴 부분만 시간을 이미 지난것 처럼 해준다. expect(sensor.status).toEqual('sensingDistance'); });
index.js 코드
if (this.powerStatus === 'on') { // 기기가 켜지는 즉시 유휴 상태로 들어간다. this.status = 'idle'; setTimeout(() => { this.status = 'sensingDistance'; }, this.reportingInterval); // setTimeout(() => {this.arr.push(2)},) // 타이머가 미뤄진다면 이 setTimeout()도 미뤄질 것, 안미뤄지면 arr은 standardArr과 똑같은 형태가 될 것. // this.arr.push(1) // console.log(this.arr) // if (this.standardArr[0] !== this.arr[0]) { // this.status = 'sensingDistance' 왜 이게 안되나 했더니 생각해보면 setTimeout(() => {this.arr.push(2)},) 아래로는 모두 동시에 실행되기에 if문의 결과도 고정적일 수 밖에 없는 것이다...와우..
원래는 주석 친 부분 처럼 배열을 이용해 조작하려 했다.
이때는 jest.advanceTimersByTime()라는 함수가 모든 타이머 함수의 지정 시간에다가 자신이 지정한 시간을 더하는 건줄 알았다.
그래서 둘을 어떻게 연결할지 고민했다.
하지만 막상 jest.advanceTimersByTime()의 뜻이 그런게 아니라는 것을 알고나니 오히려 단순해졌다.
그저 setTimeout()을 사용해 this.status = 'sensingDistance'; 라는 구문을 실행시켜 sensor의 상태만 this.reportingInterval 밀리세컨드 이후에 바꾸면 되는 것이었다.
개념을 정확히 알고나니 문제 해결이 훨씬 수월했다.
항상 개념을 제대로 이해해보자..!
▶ 느낀 점
이번에도 많은 시행착오가 있었지만 코드의 분량자체도 많지 않은 편이었고
많이 막힐 땐 팀원 분들에게 문제 해결의 소스를 얻을 수 있었다.
덕분에 제 시간 내에 여유롭게 마무리 지었고 남은 하루는 알고리즘과 지난주 덜했던 부분을 다시 해보고자 한다.
아 물론 팀 과제도 해야하고..!
오늘 하루도 고생 많았습니다 모두들! ;)
▶ 공부 시 참고 링크들
https://jest-bot.github.io/jest/docs/api.html#aftereachfn
https://blog.naver.com/wkdgusrhkd97
https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_33 (0) 2022.02.12 항해 99 5기 TIL_32 (0) 2022.02.11 항해 99 5기 TIL_30 (0) 2022.02.09 항해 99 5기 TIL_29 (0) 2022.02.07 항해 99 5기 WIL_4 (0) 2022.02.06