Разобрать токен с кипарисом - PullRequest
0 голосов
/ 07 марта 2019

чертовски разочарован. Я новичок в тестировании, а также в javascript, но я должен написать тесты для моего холостяка.

, чтобы тестируемое веб-приложение имело пространство входа в систему, в котором можно купить различные продукты. Я могу получить два разных жетона. первая касается моего идентификатора пользователя, а вторая - о «корзине» (на самом деле это не корзина, потому что процесс покупки - это инвестиционный процесс, а продукт - недвижимость)

Итак, Кипарис предлагает это

    cy.request('POST', 'https://sso.corp.com/auth', { username: 'foo', password: 'bar' })
  .then((response) => {
    // pull out the location redirect
    const loc = response.headers['Location']

    // parse out the token from the url (assuming its in there)
    const token = parseOutMyToken(loc)

    // do something with the token that your web application expects
    // likely the same behavior as what your SSO does under the hood
    // assuming it handles query string tokens like this
    cy.visit('http://localhost:8080?token=' + token)

    // if you don't need to work with the token you can sometimes
    // just visit the location header directly
    cy.visit(loc)
  })

Я сделал это:

  it('strategy #1: parse token from HTML', function () {
            // if we cannot change our server code to make it easier
            // to parse out the CSRF token, we can simply use cy.request
            // to fetch the login page, and then parse the HTML contents
            // to find the CSRF token embedded in the page
            cy.request()
                .its('body')
                .then((body) => {
                    // we can use Cypress.$ to parse the string body
                    // thus enabling us to query into it easily
                    const $html = Cypress.$(body)
                    const csrf = $html.find('#user_profile__token[name=user_profile[_token]]').val()

                    cy.loginByCSRF(csrf)
                        .then((resp) => {
                            expect(resp.status).to.eq(200)
                            expect(resp.body).to.include("<h2>dashboard.html</h2>")
                        })
                })
        });

Это не сработало, хотя я нашел это на странице github. кто-нибудь из вас имеет какие-либо идеи?

TokenID пользователя: input#user_profile__token[name=user_profile[_token]]

Идентификатор токена продукта: input#product_filter__token[name=product_filter[_token]]

Задача - не только анализировать токены, но и сохранять их во время тестирования в кипарисе.

Пожалуйста, помогите

Мой код, который вызывает эту ошибку 401:

import * as LogConst from 'C:\\Users\\Kristi\\Desktop\\BATests\\tests\\cypress\\fixtures\\Login_Data.json'

describe('Login & Selection of Investment AIF Dr. Peters', function () {

    before(function () {
        cy.visit('https://' + LogConst.server.name + ':' + LogConst.server.password + '@dev.capitalpioneers.de/')
        cy.contains('Login').click();
        cy.url()
            .should('include', '/login')});

      it('logs in', function () {
            cy.get('#email.form-control')
                .type(LogConst.TestUserCostumer.usercos);
            cy.get('#password.form-control')
                .type(LogConst.TestUserCostumer.usercospass);
                      cy.contains('Anmelden').click();
            cy.url().shoul('include','/investor');
        });

     it('product selection the Dr. Peters Product', function () {
            cy.contains('Produkt').click();
            cy.url()
                .should('include', '/produkte');


 it('selects Dr. Peters AIF Product', function () {


            cy.contains('Dr. Peters').click();
            cy.url().should('include', '\/produkt/hotelimmobilie-aachen/');
            cy.get('#sum_slider[type=range]')
                .invoke('val', 50000)
                .trigger('change')
        });


 it('download nessecary docs', function () {
            cy.get('#ga-btn-invest-now-product-detail-hotelimmobilie-aachen').click();
            cy.contains('Fondsprospekt').click();
            cy.contains('Wesentlichen Anlegerinformationen').click()
    });

   it('sets the right checks', function () {
           cy.get('#pre_check_inGermany').click({force: true});
           cy.get('#pre_check_readDocument1').click({force: true});
           cy.get('#pre_check_readDocument2').click({force: true});
           cy.get('button').contains('Weiter').click();
    });

});

1 Ответ

0 голосов
/ 07 марта 2019

То есть настоящее приложение никогда не будет хранить токены в HTML, поэтому я предполагаю, что именно поэтому у вас возникли проблемы.

Если ваш токен должен оказаться в localStorage, вы можете попробовать следующее

cy.visit(...)
cy.get('input#user_profile__token').then( $el => {
  const token =$el.attr('name')
  // Parse the token if needed, if it's not in the correct format
  window.localStorage.setItem('user_token', token)

})

Но опять же, не совсем понятно, что вы пытаетесь сделать с токеном.

...