Day 24 cypress取得mock的回传资料

今天我们来针对API call来进行模拟,因为测试画面不一定都只是点选之类的模拟测试,这时候我们可能需要透过axios或者是fetch的方式取得server回传的资料进行验证,这时候我们可以透过cy.server(v6.0之前)与cy.intercept(v6.0之後)的方式设定回传的statusCode以及资料.

improt axios from 'axios'

const handleSubmit = async () => {
	const res = await axios.post('url', body);
	const { data, status } = data;
	
	if (status === '200') {
		history.push('/rooms')
	}	
}

我们可能可以使用cy.server的方式建立一个server mock一个回传的资料

it('should return login success', () => {
    cy.server().route({
      url: 'http://localhost:3001/login',
      method: 'POST',
      status: 200,
      response: {
        success: true
      }
    });
  });

让回传的资料,是正确的.然後上面的范例是6.0之前的版本,再来我们来看v6.0之後出的intercept(拦截器)

cy.intercept('POST', '**/login', {
      success: true
  }).as('loginAuth');

cy.visit('/')
  .get('[role="account"]')
  .type('123')
  .get('[role="password"]')
  .type('123')
  .get('button')
  .click();

cy.wait('@loginAuth');
cy.url().should('eq', 'http://localhost:3001/rooms');

在这边我们可以设定一个API Call的拦截器,并且回传success: true

这时我们可以透过cy.wait的方式等待API回传资料完成,并且确认url来到正确的位置

.as主要是给一个action的alias,当我们用as取名之後,可以使用@加上alias我们就可以取用那个定义

参考文献:

  1. https://docs.cypress.io/api/commands/as#Syntax

<<:  好好介绍产品

>>:  [Day24] Bind Shell / Reverse Shell

DAY25 MongoDB 自订角色与使用者

DAY25 MongoDB 自订角色与使用者 前言 MongoDB 内的登入需要输入 使用者(use...

Day 14:专案02 - PTT C_chat版爬虫01 | 爬虫简介、request和response、Requests

⚠行前通知 先前已经学过Python但想学爬虫的人可以回来罗~ 从今天起就开始大家最期待的网页爬虫的...

Day 06 JavaScript/Rails AJAX

阿修的说文解字 AJAX 的全名是 Asynchronous JavaScript and XML ...

[Day07] 赋值运算子、逗号运算子、逻辑运算子笔记

赋值运算子(Assignment operators) 在 Javascript 里运算有递增的写法...

解决 "No manual entry for gcc" 的记录

问题: $ man gcc No manual entry for gcc 看到这个方法,但是失败了...