Vue BDD

Vue BDD - Cypress Mock Api

eddie0329 2020. 10. 13. 17:13
๋ฐ˜์‘ํ˜•

๐Ÿ“Œ ๋ชฉ์ฐจ

  • Introduction
  • Cypress api mock ํ•˜๊ธฐ
  • Conclusion
  • Reference

๐Ÿ“Œ Introduction

์•ˆ๋…•ํ•˜์„ธ์š”. BDD๋งˆ์ง€๋ง‰ ์‹œ๊ฐ„์œผ๋กœ ์ด์ œ Cypress์—์„œ api call๋ฅผ mock ํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ํ•ด๋‹น ์ฝ”๋“œ๋Š” ์—ฌ๊ธฐ์—์„œ ํ™•์ธํ•˜์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•ด๋‹น ์˜ˆ์ œ๋Š” jsonplaceholder์—์„œ todo๋ฅผ ํ•˜๋‚˜ ๋ฐ˜ํ™˜ํ•˜๋Š” ์˜ˆ์ œ ์ž…๋‹ˆ๋‹ค.

๐Ÿ“Œ Cypress api mock ํ•˜๊ธฐ

API๋ฅผ mock ํ•˜๊ธฐ์ „์— ๋จผ์ € ํ–‰๋™์„ ์ •์˜ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

  • Todo์˜ ์ œ๋ชฉ์€ 'hello'๋ผ๊ณ  ์“ฐ์—ฌ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
Feature: Todo
  Background: 
    Given I am on the main page

  Scenario: Todo display
    Then I can see Todo with text:
    |title|hello|

์ด๋ ‡๊ฒŒ ์“ด Gherkin์œผ๋กœ cypress๋Š” ์ด๋ ‡๊ฒŒ ์ฝ”๋”ฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.


const { visit, the } = cy;

Given("I am on the main page", () => {
  cy.server();
  cy.route("https://jsonplaceholder.typicode.com/posts/1", {
    title: "hello",
  });
  visit("/");
});

Then("I can see Todo with text:", (rawData) => {
  const stats = rawData.rowsHash();
  const title = stats["title"];
  cy.log(stats);
  the("todo").contains(title);
});

Given("I am on the main page", ...)๋ถ€๋ถ„์„ ๋ณด๋ฉด cypress server๋ฅผ ๋จผ์ € ๋„์›Œ์ค๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  route๋ฅผ ํ†ตํ•ด ๋ฐ›๋Š” ๊ฒƒ์„ ์ƒ์„ธํ•˜๊ฒŒ ์ ์–ด์ค๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ์ ์–ด์ฃผ๋ฉด

import * as axios from "axios";

export const fetchTodos = () => {
  return axios.get("https://jsonplaceholder.typicode.com/posts/1");
};

fetchTodos์˜ response๋Š” { title: "hello" }๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.

๐Ÿ“Œ Conclusion

Cypress์—์„œ api๋ฅผ mock ํ•˜๋Š” ๋ถ€๋ถ„์€ ๊ทธ๋ ‡๊ฒŒ ์–ด๋ ต์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋‹ค๋งŒ ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ•˜์ง€๋Š” ๋งค์šฐ ์–ด๋ ต์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  api๋ฅผ mockํ•ด์ฃผ๋Š” ๊ฒƒ์€ integration test์˜ ๋ช…๋ชฉ์— ๋งŽ์ด ๋ฒ—์–ด๋‚ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋ฏ€๋กœ ์• ์ดˆ์— Gherkin์„ ์ž˜ ์ ์–ด์ค„ ํ•„์š”๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์ƒ์„ธํ•œ ๋ถ€๋ถ„๋“ค๋งˆ๋‹ค testing์„ ์ง„ํ–‰ํ•˜๋ฉด ์ข‹๊ฒ ์ง€๋งŒ ๊ทธ๋Ÿฐ ๋ถ€๋ถ„์€ ์ด๋ฏธ tdd์—์„œ unit test์—์„œ ๋งŽ์ด ๊ฑธ๋Ÿฌ์กŒ์„๊ฑฐ๋ผ ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ์ตœ๋Œ€ํ•œ ๋ฌถ์–ด์„œ ์ „์ฒด์ ์ธ ํ๋ฆ„์œผ๋กœ์จ์˜ integration์„ ์ง„ํ–‰ํ•˜๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿผ ๋‹ค์Œ ํฌ์ŠคํŒ…์—์„œ ๋งŒ๋‚˜์š”~~ ๐Ÿ˜Ž

๐Ÿ“Œ Reference

๋ฐ˜์‘ํ˜•