问题
I have almost 100 specs files including multiple tests. I want run all these specs files by login one time. I dont want my cypress should login process every time on every spec file It it possible to persist single login for all spec files
回答1:
This is the recommend approach that Cypress.io suggest you use, as this is quite the anti-pattern.
Cypress Docs
Anti-Pattern: Sharing page objects, using your UI to log in, and not taking shortcuts.
Best Practice: Test specs in isolation, programmatically log into your application, and take control of your application’s state.
You should have one spec file/few tests that do actually test your login screen/functionality, to confirm that is does indeed work.
But then any other time you should grammatically log into your account via an API and store the credentials in a cookie or token.
That way you should be able to bypass the login screen.
Once you have the API working you can add it into a before hook in the appropriate place.
回答2:
Take a look at our "Logging in" recipes https://github.com/cypress-io/cypress-example-recipes#logging-in-recipes - most of them log in once using before hook, and then save the cookie / token in a local variable and set it again and again in beforeEach hook
回答3:
Please see code:
I am storing data in localstorage when login completed
i am calling login method in first file and able to access that localstorate in first file
but in 2nd spec file i am not able to access that token and not logining
// commands.js
Cypress.Commands.add("SignIn", () => {
cy.visit("https://app-dev.partie.com/");
const loginBtn = "section.btn-group > a.btn.btn-outline";
const userNameField = 'input[type="text"]';
const passwordField = 'input[type="password"]';
const loginFormBtn = ".bg-blue";
cy.get(loginBtn).click();
cy.get(userNameField)
.type("usrename")
.get(passwordField)
.type("!password");
cy.get(loginFormBtn).click();
cy.wait(3000);
cy.setLocalStorage("jwt", "this is token");
cy.setCookie('foo', 'bar')
});
/////// first test spec file and i am abale to access local storate ///////
before(() => {
cy.SignIn()
cy.saveLocalStorage();
});
beforeEach(() => {
cy.restoreLocalStorage();
});
it("should exist identity in localStorage", () => {
cy.getLocalStorage("jwt").then(token => {
cy.log("jwt", token);
});
cy.getCookie('foo').should('have.property', 'value', 'bar')
});
//////// 2nd test spec file and im not able to access token //////////////////
afterEach(() => {
cy.saveLocalStorage();
});
beforeEach(() => {
cy.restoreLocalStorage();
});
it("should exist identity in localStorage", () => {
cy.getLocalStorage("jwt").then(token => {
cy.log("jwt", token);
});
});
来源:https://stackoverflow.com/questions/59266282/cypress-i-want-run-tests-in-100-spec-files-by-login-one-time-and-persist-login