Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 비전공이지만 개발자로 먹고삽니다
- 올림픽 통계 서비스 최적화
- Babel과 Webpack
- peerdependencies
- DOM
- 모던 자바스크립트 Deep Dive
- 제너레이터와 async/await
- 프로그래머스
- 커리어
- 자바스크립트 패턴
- 블로그 서비스 최적화
- 스코프
- 프로퍼티 어트리뷰트
- 인터넷 장비
- ES6함수 추가기능
- 전역변수의문제점
- const
- Property Attribute
- package management
- 빌트인 객체
- 자바스크립트
- 자바스크립트 딥다이브
- 이벤트
- Set과 Map
- 이미지 갤러리 최적화
- 디스트럭처링
- 딥다이브
- 프론트엔드 성능 최적화 가이드
- 브라우저의 렌더링 과정
- var 사용금지
Archives
- Today
- Total
Dev Blog
Section8: More on Mocking & Diving Deeper 본문
Online Lectures/JavaScript Unit Testing - The Practical
Section8: More on Mocking & Diving Deeper
Nomad Kim 2023. 4. 5. 06:43- Mocking Global Objects & Functions
- Mocking Frontend Features
- Examples
Case1. fetch is a globally available function which is not imported.
Thus, cannot use vi.mock to replace a module in this case. SubGlobal method allows us to replace globally available objects and functions with implementations. Then, Production codes are not effected!
sendDataRequest function
export async function sendDataRequest(data) {
const response = await fetch("https://dummy-site.dev/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
// body: data,
});
const responseData = await response.json();
if (!response.ok) {
throw new HttpError(
response.status,
"Sending the request failed.",
responseData
);
}
return responseData;
}
https.test.js
const testResponseData = {
testKey: "testData",
};
// await fetch('https://dummy-site.dev/posts', { method: 'POST',...in sendDataRequest function
const testFetch = vi.fn((url, options) => {
return new Promise((resolve, reject) => {
/**
* @description test JSON.stringify(required data conversion) works or not
*/
if (typeof options.body !== "string") return reject("Not a string.");
const testResponse = {
//if (!response.ok) { ... in sendDataRequest function
ok: true,
//const responseData = await response.json(); ... in sendDataRequest function
json() {
return new Promise((resolve, reject) => {
resolve(testResponseData);
});
},
};
resolve(testResponse);
});
});
// SubGlobal method allows us to replace globally available objects
// and functions with implementations
vi.stubGlobal("fetch", testFetch);
it("should convert the provided data to JSON before sending the request", async () => {
const testData = { key: "test" };
let errorMessage;
try {
await sendDataRequest(testData);
} catch (error) {
errorMessage = error;
}
expect(errorMessage).not.toBe("Not a string.");
});
Case2. non-ok response. use mockImplementationOnce method
In case of difference on the arguments in response.
it("should throw and httpError in case of non-ok responses", () => {
testFetch.mockImplementationOnce((url, options) => {
return new Promise((resolve, reject) => {
const testResponse = {
ok: false,
json() {
return new Promise((resolve, reject) => {
resolve(testResponseData);
});
},
};
resolve(testResponse);
});
});
const testData = { key: "test" };
return expect(sendDataRequest(testData)).rejects.toBeInstanceOf(HttpError);
});
Case3. local mock values
const testTitle = "Test title";
const testContent = "Test content";
let testFormData;
describe("extractPostData()", () => {
beforeEach(() => {
// usage of local mock values!
testFormData = {
title: testTitle,
content: testContent,
get(identifier) {
return this[identifier];
},
};
});
it("should extract title and content from the provided form data", () => {
const data = extractPostData(testFormData);
expect(data.title).toBe(testTitle);
expect(data.content).toBe(testContent);
});
});
'Online Lectures > JavaScript Unit Testing - The Practical' 카테고리의 다른 글
Section9: Testing & the DOM(Frontend Javascript Testing) (0) | 2023.04.05 |
---|---|
Section7: Mocking & Spies: Dealing with Side Effects (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 |
Comments