多年来,我一直在为此扯头发-我希望有人能帮助我:)
我已经尝试将赛普拉斯的网络请求存根已有很长时间了。
commands.js
Cypress.Commands.add('login', (
email = 'email',
password = 'pass'
) => {
cy.server();
cy.visit('url');
cy.get('input[name="username"').type(email);
cy.get('form').submit();
cy.get('input[name="password"').type(password);
cy.get('form').submit();
});
mock.js
describe('mock', function() {
it('user can login', function() {
cy.login();
cy.get('main[role="main"]');
cy.route('GET',
'**/getIncentives*',
{info: {}, results: {}}
).as('oppty');
cy.wait('@oppty');
});
});
这里的任何帮助将不胜感激-我疯了!
非常感谢,
奥利
答案 0 :(得分:3)
Currently, Cypress cy.route
can only stub network requests that use XHRs
原生HTML表单元素不使用XMLHTTPRequest,因此不能使用cy.route
对其进行存根。
大多数人不会遇到此问题,因为使用本机HTML表单是not as common nowadays
您也在waiting
的路线上,但实际上并未在测试中做任何事情。您的测试应如下所示:
cy.route('GET',
'**/getIncentives*',
{info: {}, results: {}}
).as('oppty');
// cypress code that would cause a network request.
cy.wait('@oppty');
答案 1 :(得分:3)
Cypress将在别名后才找到网络请求 。您问题中的代码表明您没有执行可能导致网络请求的操作:
cy.route('GET',
'**/getIncentives*',
{info: {}, results: {}}
).as('oppty');
// cypress expected something to cause a network request here
cy.wait('@oppty');
您应该在测试中将调用移至route
的前面,或者在调用route
后移至导致请求的代码。
答案 2 :(得分:0)
还请注意,cy.route()可能不适用于服务器端呈现(显然)。
我在使用NextJs时遇到了这个问题,并通过首先调用其他页面,然后在客户端上导航到我实际要测试的页面来解决此问题。
像这样:
describe('test cy.route', function() {
it( 'test 1', () => {
cy.server();
cy.route({
method: 'GET',
url: /.*\/api\/someApiCall/,
response: { 'someApiResponse': 'ok' },
status: 200
} ).as('myRouteAlias');
// go to start page: first page is server side rendered. cy.route doesn't work.
cy.visit('/');
// go to page to be tested: client side, cy.route works then.
cy.get( `a[href="/pageToBeTested"` ).should('exist').click();
// wait for page loaded
cy.url().should('include', 'pageToBeTested' );
// do something that requests '/api/someApiCall'.
invokeFunctionThatDoesTheRequest();
// wait for the request
cy.wait('@myRouteAlias');
});
});