使用夹具时,赛普拉斯不会存根我的请求

时间:2021-03-17 19:49:45

标签: javascript cypress

我正在尝试使用 Cypress 为我的 Angular 应用程序创建 e2e 测试。到目前为止,我已经对基础知识进行了排序,现在我正在尝试存根网络请求。

我创建了一些装置并创建了一个自定义命令:

Cypress.Commands.add('login', (email, password, happy = false) => {
    let auth_url = Cypress.env('auth_url');
    console.log(auth_url);

    cy.get('[data-cy=email]').as('email');
    cy.get('[data-cy=password]').as('password');
    cy.get('[data-cy=login-form]').as('form');

    cy.location('pathname').should('equal', '/login');

    cy.get('@email').type(email);
    cy.get('@password').type(password);

    cy.get('@form').submit();

    cy.fixture(happy ? 'successful-login.json' : 'failed-login.json').then((json) => {
        console.log(json);
        cy.intercept(`${auth_url}/connect/token`, json).then(() => {
            if (!happy) return;

            cy.fixture('current-user.json').then((currentUser) => {
                console.log(currentUser);
                cy.intercept(`/users/**`, currentUser);
            });
        });;
    });
});

我的固定装置是: successful-login.json

{
    "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjRGNEVBQzE4N0Y5QUM1MTE4NjhFNTQ5OTA5RUIzOEQxIiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE2MTYwMDgxNTksImV4cCI6MTYxNjAxMTc1OSwiaXNzIjoiaHR0cHM6Ly9zeHAtZGV2ZWxvcC1pZGVudGl0eS5henVyZXdlYnNpdGVzLm5ldCIsImF1ZCI6WyJzeHAiLCJpZGVudGl0eS1zZXJ2ZXIiXSwiY2xpZW50X2lkIjoiY2xpZW50Iiwic3ViIjoiYTIzM2Q0MDgtMjVjMi00ODZhLWFlMzgtOTMzMTk5YjU2OWRkIiwiYXV0aF90aW1lIjoxNjE2MDA4MTU4LCJpZHAiOiJsb2NhbCIsInJvbGUiOiJBZG1pbmlzdHJhdG9yIiwicGVybWlzc2lvbiI6WyJ1c2VyczpyZWFkIiwidXNlcnM6d3JpdGUiXSwianRpIjoiQTRDNjREMzk0RTcyNEY3QUE1NzRFQUNEMjA2ODM4RkIiLCJpYXQiOjE2MTYwMDgxNTksInNjb3BlIjpbImlkZW50aXR5OnJlYWQiLCJpZGVudGl0eTp3cml0ZSIsInN4cDpyZWFkIiwic3hwOndyaXRlIl0sImFtciI6WyJwd2QiXX0.e-TX3u3o8UJZ9nq7nyuMFWfRyjEh55CwWQSHhfFxt677_qCu6pJ1cuHHOMjMV0lc-hTXjbe-4lZ7oOVfOZA_gByFo6mFpq8co__Npj1YpMt18LOSuewspKldffgCZQm2wIKTqSmMIQoFDRoUmAmcBsbJZIqSx4KMYBz7OfsBmdU7TeNi8bjtLcglzBxgYko7njJuC9j1EarR9BC-tjPIb0eoROclfQlPcYb05T4RRMzi3dpFExEXzFMaiMnR8_q0VOPWzeL0phFcjm-r1nVTVvrRcCtvI3GPPxr5EshT4XHcg6pmxx8BUlWXI6u1gSnWShmvXP5n87HJTCjsJh8sEQ",
    "expires_in": 3600,
    "token_type": "Bearer",
    "scope": "identity:read identity:write sxp:read sxp:write"
}

failed-login.json

{ "error": "invalid_grant", "error_description": "invalid_username_or_password" }

最后,current-user.json

{
    "success": true,
    "failure": false,
    "error": null,
    "result": {
        "jobTitle": null,
        "image": null,
        "createdBy": "00000000-0000-0000-0000-000000000000",
        "updatedBy": "00000000-0000-0000-0000-000000000000",
        "dateCreated": "2021-02-26T11:23:18.074899",
        "dateUpdated": "2021-02-26T11:23:18.0749379",
        "deleted": false,
        "roles": null,
        "id": "a233d408-25c2-486a-ae38-933199b569dd",
        "emailConfirmed": true,
        "concurrencyStamp": "0246797d-fd93-4723-a142-95d5213f9ec7",
        "phoneNumber": null,
        "phoneNumberConfirmed": false,
        "twoFactorEnabled": false,
        "lockoutEnd": "2021-03-17T16:04:59.7781333+00:00",
        "lockoutEnabled": true,
        "accessFailedCount": 0
    },
    "message": null
}

规范文件如下所示:

/// <reference types="Cypress" />

describe('login workflow', () => {
    it('does not work with wront credentials', () => {
        const email = 'user@example.com';
        const password = 'test';

        cy.visit('/');

        cy.login(email, password).as('loginRequest').then(() => {
            cy.contains('.mat-simple-snackbar span', 'Invalid username or password.');
        });
    });

    it('happy path test', () => {
        const email = 'user@example.com';
        const password = 'test';

        cy.visit('/');
        cy.location('pathname').should('equal', '/login');

        cy.login(email, password, true).as('loginRequest').then(() => {
            cy.location('pathname').should('equal', '/');
        });
    });
});

我的问题是,即使测试都说路由被截断了:

enter image description here

实际请求不是:

enter image description here

第一次测试通过,因为用户名和密码不正确,即使没有对响应进行存根,但第二次测试失败了:

enter image description here

因为它不会存根响应:

enter image description here

有人知道我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

在先前拦截的 .then() 内设置新拦截似乎有问题。在最后一次拦截之后没有任何执行会触发它。

由于拦截应该在触发发生之前设置,以下应该是(几乎)逻辑上等效的,

Cypress.Commands.add('login', (email, password, happy = false) => {

  cy.intercept(`/users/**`, { fixture: 'current-user.json' });

  const auth_url = Cypress.env('auth_url');
  const loginFixture = happy ? 'successful-login.json' : 'failed-login.json';
  cy.intercept(`${auth_url}/connect/token`, { fixture: loginFixture });

  cy.get('[data-cy=email]').as('email');
  cy.get('[data-cy=password]').as('password');
  cy.get('[data-cy=login-form]').as('form');

  cy.location('pathname').should('equal', '/login');

  cy.get('@email').type(email);
  cy.get('@password').type(password);

  cy.get('@form').submit();
});

唯一的区别是即使 /users 拦截失败,也会设置 auth 拦截,但您无论如何都在控制该结果(使用 happy),因此这应该产生相同的结果结果