In Cypress, set a token in localStorage before test

后端 未结 5 2025
滥情空心
滥情空心 2021-01-31 15:35

I want to login and set a localStorage token on the client (specifically jwt)

How can I accomplish this using cy.request, as suggested in the C

5条回答
  •  天涯浪人
    2021-01-31 16:02

    I've used something along the lines of bkuceras answer for a while now. Recently I've run into an issue when testing multiple roles/logins throughout tests. Basically what is happening is I log in as an admin and do one test, then I log in as a non admin and do a second test. The first test runs fine and ends (cypress clears local storage) however there are still some xhr requests running from the first test when the second test starts. These xhr requests no longer see the token which triggers my app to see a 401 unauthorized error and clear local storage (including my non admin token I have set). Now the 2nd test fails because that non admin token is not available in local storage.

    Ultimately my solution was to prefetch the token before the test then set the token in the onBeforeLoad function of visit. This ensures the token is not cleared by any race condition before your visit command.

    cy.visit('/app', {
        onBeforeLoad: function (window) {
            window.localStorage.setItem('token', myToken);
        }
    })
    

    Really this is a pretty unique edge case, but heres hoping it may help someone as I've spent many hours finding this solution.

提交回复
热议问题