简体   繁体   English

使用 Cypress 在按钮单击时模拟 GET api

[英]Mocking a GET api on button click using Cypress

I'm looking for a way to mock an existing API's response on a button click.我正在寻找一种在单击按钮时模拟现有 API 响应的方法。 When the button, say button A is clicked, the page routes to, let's say #/create-something .当按钮,比如说按钮 A 被点击时,页面会路由到,比如说#/create-something

On the FE, there is a loader shown, while in the background there are two XHR requests being made.在 FE 上,显示了一个加载程序,而在后台有两个 XHR 请求正在发出。 These two API's response are used to populate two form fields on #/create-something .这两个 API 的响应用于填充#/create-something上的两个表单字段。

The page throws a console error if I don't load these two api's.如果我不加载这两个 api,页面会抛出一个控制台错误。 So, I want to mock these two api's and populate the two form fields using these mocked response.所以,我想模拟这两个 api 并使用这些模拟响应填充两个表单字段。

This is what I'm looking to perform -这就是我想要表演的 -

  1. Click on button A点击按钮A
  2. Mock the two API's so that form fields X and Y are populated based on response of mocked API.模拟这两个 API,以便根据模拟 API 的响应填充表单字段 X 和 Y。
  3. Perform some form actions.执行一些表单操作。

I have not done or written code for this part since I'm not familiar with how to go about this problem.由于我不熟悉如何解决此问题,因此我没有为此部分完成或编写代码。 I have gone through this tutorial but not able to understand if this is the correct way/approach to solve this issue.我已经阅读了教程,但无法理解这是否是解决此问题的正确方法/方法。

Edit 1 : I am adding an example.编辑 1:我正在添加一个示例。 Let's say I'm hitting this URL - Cats On the initial page load, there are a couple of XHR calls being made.假设我正在访问这个 URL - Cats在初始页面加载时,有几个 XHR 调用被执行。 I want to mock the me and the cats API call using fixtures.我想使用夹具来模拟mecats API 调用。

I have a urls file which contains the routes -我有一个包含路由的urls文件 -

urls.js网址.js

 export const me='/users/me';
 export const cats='3/gallery/r/cats'

In my cats.spec.js folder, I have this code在我的cats.spec.js文件夹中,我有这个代码

   import {
       me,
       cats  
    } from '../cats'

 context('Checking if mocking can be done',()=>{
   const mockingAPI = () =>{
       cy.server();
       cy.route(me, 'fixtures:me-mock.json);
       cy.route(cats,'fixtures:me-cats.json);
       cy.wait(2000);
        }

   describe('Actual mock and tests',()=>{
       before(mockingAPI());

       it('lets add some tests',()=>{
        cy.visit('/');

         })

  })
})

PS - If this has already been asked, please point me to the same. PS - 如果这已经被问到,请指点我。

Cypress allows you to stub network requests. Cypress 允许您存根网络请求。 When your application makes a request to a particular endpoint, you can intercept it to return a mocked response.当您的应用程序向特定端点发出请求时,您可以拦截它以返回模拟响应。 You can either use fixtures for your mock response or just pass a plain object as the third argument to cy.request() .您可以为模拟响应使用固定装置,也可以将普通对象作为第三个参数传递给cy.request()

Your setup should be something like this:你的设置应该是这样的:

it('should...', () => {

  cy.server();
  cy.visit('/');

  // load your mock data
  cy.fixture('me-mock.json').as('meJSON');
  cy.fixture('me-cats.json').as('catsJSON');

  // stub the two server requests to return your mock data
  // make sure you use the full URL
  cy.route('GET', serverUrl + '/users/me', '@meJSON').as('me');
  cy.route('GET', serverUrl + '3/gallery/r/cats', '@catsJSON').as('cats');

  // trigger the requests
  cy.get('#createSomething').click();

  // wait for both requests to resolve
  cy.wait(['@me', '@cats']);

  // then trigger more actions, make assertions, etc...

});

But make sure you use the full URL when defining the route.但是请确保在定义路由时使用完整的 URL。

I could see that in your question there are no fixtures declared in the before call.我可以看到,在您的问题中,没有在 before 调用中声明固定装置。 I assume that the json files resides in your fixture folder.我假设 json 文件位于您的夹具文件夹中。 Please add/correct the example so it has a compile-able code.请添加/更正示例,使其具有可编译的代码。 Also correct the api routes so they have the same behavior (either add the leading forward slash or remove it and correct the visit method).还要更正 api 路由,使它们具有相同的行为(添加前导正斜杠或删除它并更正访问方法)。 Make sure that the routes are the one that are called on your actual (live) application and you are mocking them correctly (with proper responses).确保路由是在您的实际(实时)应用程序上调用的路由,并且您正在正确模拟它们(具有正确的响应)。 Move the visit in your before method.在你之前的方法中移动访问。 Remove the wait call because it could hide some errors that needs to be addressed.删除等待调用,因为它可能隐藏一些需要解决的错误。 Check if the page loads on cy.visit() and that all of the necessary 'GET' calls are mocked.检查页面是否在 cy.visit() 上加载并且所有必要的“GET”调用都被模拟。 If you mock all of your get methods and authenticate properly (if it is applicable) you should see the content that you need.如果您模拟所有 get 方法并正确进行身份验证(如果适用),您应该会看到您需要的内容。 There is only one problem that the test is not written properly and could not find the query selector that you are looking for but this is not part of the question.只有一个问题是测试没有正确编写并且找不到您正在寻找的查询选择器,但这不是问题的一部分。

You can try any mock server, they let you configure a static MockAPI that will always return what's configured at it.您可以尝试任何模拟服务器,它们允许您配置静态 MockAPI,该 API 将始终返回配置的内容。

For personal use i recommend Wiremock as it can be run as a standalone server pretty quickly.对于个人使用,我推荐Wiremock,因为它可以非常快速地作为独立服务器运行。 Also you can integrate it as part of your maven test goal .您也可以将其集成为Maven 测试目标的一部分

Of course the only point of using this tool over something Cypress already does is maybe that you can save an exisiting API as static, for example you can point it to production, save every result and then re-use it as a test.当然,在 Cypress 已经做的事情上使用此工具的唯一目的可能是您可以将现有 API 保存为静态,例如您可以将其指向生产,保存每个结果,然后将其重新用作测试。

Another options:另一种选择:

  • JsonServer : Created with for front-end developers who need a quick back-end for prototyping and mocking. JsonServer :为需要快速后端进行原型设计和模拟的前端开发人员创建。
  • MockServer : This is an open source mocking framework for HTTP and HTTPS released under the Apache License. MockServer :这是在 Apache 许可下发布的用于 HTTP 和 HTTPS 的开源模拟框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM