일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- const
- Set과 Map
- 자바스크립트 딥다이브
- peerdependencies
- 브라우저의 렌더링 과정
- 인터넷 장비
- 디스트럭처링
- 전역변수의문제점
- 이벤트
- 비전공이지만 개발자로 먹고삽니다
- Property Attribute
- 모던 자바스크립트 Deep Dive
- DOM
- 빌트인 객체
- var 사용금지
- 제너레이터와 async/await
- ES6함수 추가기능
- 올림픽 통계 서비스 최적화
- 이미지 갤러리 최적화
- 프론트엔드 성능 최적화 가이드
- 커리어
- 블로그 서비스 최적화
- 자바스크립트 패턴
- package management
- Babel과 Webpack
- 딥다이브
- 자바스크립트
- 프로퍼티 어트리뷰트
- 스코프
- 프로그래머스
- Today
- Total
Dev Blog
Section7: Mocking & Spies: Dealing with Side Effects 본문
Section7: Mocking & Spies: Dealing with Side Effects
Nomad Kim 2023. 4. 5. 06:40Dealing with Side Effects
- Dealing with Side Effects & External Dependencies
- Understanding Spies & Mocks
- Examples
Why need?
- In some cases, test interacts with upper system such as hard drive, database outside of program and code.
- Means that there could be side effects.
- e.g. important files or data could be deleted or edited accidentally.
spy
fn creates an empty function that keeps track of any function executions of that function. Means calls to the function. It also keeps track of arguments that are provided with those calls.
const logger = vi.fn();
return expect(writeData(testData, testFileName)).resolves.toBeUndefined();
This code makes error. TypeError: Cannot read properties of undefined (reading 'then') Because spy doesn't have methods. In this case, use fs.writeFile that is run in writeData function.
import { it, expect, vi } from "vitest";
import { promises as fs } from "fs";
import writeData from "./io";
it("should execute the writeFile method", () => {
const testData = "Test";
const testFileName = "test.txt";
writeData(testData, testFileName);
expect(fs.writeFile).toBeCalled();
});
mock
In case that there are not unusable modules we don't own, we cannot use spy. In this example case, it doesn't receive writeFile as an argument.
Mock works with built in or third-party module and own modules, own files.
- This starts Vitest's or Jest's auto-mocking algorithm finding module by name or path and replace all the functions with empty spy functions.
- And importantly, vi.mock is hoisted automatically to the top for mocking away before importing.
vi.mock("fs");
/**
* @description By setting the second argument, able to return wanted outcome
*/
vi.mock("path", () => {
return {
default: {
join: (...args) => {
/**
* @description last argument is filename. In this case, testFileName.
* const storagePath = path.join(process.cwd(), "data", filename);
* */
return args[args.length - 1];
},
},
};
});
it("should execute the writeFile method", () => {
const testData = "Test";
const testFileName = "test.txt";
writeData(testData, testFileName);
expect(fs.writeFile).toBeCalledWith(testFileName, testData);
});
For multiple test, can set global mock setting(__mocks__).
Then, codes using resolves method will works because it looks for ‘__mocks__’ folder and promises function for using returned Promise of writeFile method.
'Online Lectures > JavaScript Unit Testing - The Practical' 카테고리의 다른 글
Section9: Testing & the DOM(Frontend Javascript Testing) (0) | 2023.04.05 |
---|---|
Section8: More on Mocking & Diving Deeper (0) | 2023.04.05 |
Section6: Advanced Testing Concepts (0) | 2023.04.05 |
Section 5: Integration Tests (0) | 2023.04.05 |
Section 4: Writing Good Tests (0) | 2023.04.05 |