前言

  • Cypress 6.0.0 开始不推荐使用 cy.server() 和 cy.route()
  • 在将来的版本中,对 cy.server() 和 cy.route() 的支持将移至插件
  • 现在优先考虑使用 cy.intercept()

作用

语法格式

  1. cy.server()
  2. cy.server(options)

options 参数

作用

  • 作为默认值,它们被合并到 cy.route() 中
  • 作为所有请求的配置行为

以下选项被合并为 cy.route() 的默认选项

Cypress系列(70)- server() 命令详解 - 图1

以下选项控制服务器,将会影响所有请求的行为

Cypress系列(70)- server() 命令详解 - 图2

命令执行结果

  • 执行结果是 null
  • 且后续不能再链接其他命令

没有参数的栗子

// 启动服务器cy.server()

  • 任何与 cy.route() 不匹配的请求都将传递到服务器,除非设置了 force404,这样请求变成 404 和拿到一个空 response
  • 与 options.ignore 函数匹配的任何请求都不会被记录或存根(logged、stubbed)
  • 将在命令日志中看到名为(XHR Stub)或(XHR)的请求

带有参数的栗子

进入演示项目目录下

注:演示项目是 cypress 提供的,如何下载可看 Cypress 系列文章的一开始几篇都有写

  1. cd C:\Users\user\Desktop\py\cypress-example-recipes\examples\logging-in__xhr-web-forms

启动演示项目

  1. npm start

浏览器访问项目

  1. http://localhost:7079/

测试代码

  1. context('route 的栗子', function () {
  2. const username = 'jane.lane'
  3. const password = 'password123'
  4. before(function () {
  5. cy.visit('http://localhost:7079/')
  6. })
  7. it('栗子1', function () {
  8. cy.server({
  9. method: 'POST',
  10. status: 503,
  11. delay: 1000,
  12. headers: {
  13. 'x-token': 'abc-123-foo-bar'
  14. }
  15. })
  16. cy.route({
  17. url: '**/login',
  18. response: {
  19. success: false,
  20. data: 'Not success'
  21. },
  22. }).as("login")
  23. cy.get("input[name=username]").type(username)
  24. cy.get("input[name=password]").type(`${password}{enter}`)
  25. cy.wait('@login').then((res) => {
  26. cy.log(res)
  27. expect(res.status).to.eq(503)
  28. expect(res.responseBody.data).to.eq('Not success')
  29. expect(res.responseHeaders).to.have.property('x-token', 'abc-123-foo-bar')
  30. })
  31. });
  32. })

测试结果

Cypress系列(70)- server() 命令详解 - 图3

启动服务器,关闭服务器的栗子

测试代码

  1. it('栗子2', function () {
  2. cy.server()
  3. cy.route({
  4. url: '**/login',
  5. method: 'POST',
  6. status: 503,
  7. response: {
  8. data:"success"
  9. }
  10. }).as("login")
  11. cy.get("input[name=username]").type(username)
  12. //第一次发出请求
  13. cy.get("input[name=password]").type(`${password}{enter}`)
  14. cy.wait('@login').then((res) => {
  15. expect(res.status).to.eq(503)
  16. // 关闭服务器
  17. cy.server({
  18. enable: false
  19. })
  20. })
  21. cy.visit('http://localhost:7079/')
  22. cy.get("input[name=username]").type(username)
  23. //第二次发出请求
  24. cy.get("input[name=password]").type(`${password}{enter}`)
  25. });

测试结果

Cypress系列(70)- server() 命令详解 - 图4
第二个请求虽然被路由监听到了,但是因为服务器关闭了,所以并没有获取路由的 status、response

注意事项

  • 可以在启动 cy.visit() 之前启动服务器 cy.server()
  • 通常,应用程序在加载时可能会立即发出初始请求(例如,对用户进行身份验证)
  • Cypress 可以在 cy.visit() 之前启动服务器并定义路由( cy.route() )
  • 下次访问时,服务器 + 路由将在应用程序加载之前立即应用

https://www.cnblogs.com/poloyy/p/13856700.html