使用API进行Oauth后,我试图访问网站(UI)。这就是我的代码。
**Command.js**
Cypress.Commands.add('login', (email, password) => {
Cypress.log({
name: 'loginViaOauth',
});
const options = {
method: 'POST',
url: 'http://IPaddress/API/oauth/token',
"body":'blah blah'
};
cy.request(options)
});
并称呼它
cy.login(myusername,mypassword) // Success here
在此之后,说我想访问网站的任何其他页面,所以我试图使用
cy.visit('/mypage')
,但似乎我尚未登录。 请有人告诉我我在做什么错吗?
答案 0 :(得分:0)
Cookie和令牌可以通过多种方式实现。我会与开发人员联系并了解这一点。
cy.setCookie('auth_key', '123key')
这是cypress.io的详细文档
https://docs.cypress.io/api/commands/setcookie.html#Syntax
StackOverFlow类似的讨论:How to set cookies within Cypress testing?
答案 1 :(得分:0)
赛普拉斯会将每个测试用例视为一个新环境。因此,如果您想在测试中保留一些Auth信息,则必须在每次测试之前和之后保存并重新加载信息。这是一个示例:
/** Session Caching */
var localStorageCache = { 'userSettings' : null, ... }; // Define keys to save/load in between tests here.
var cookieCache = { 'jwtToken' : null, 'searchSessionID' : null, ... };
Cypress.Commands.add('saveBrowserSession', function(options = {}){
_.forEach(_.keys(localStorageCache), function(storageKey){
localStorageCache[storageKey] = localStorage.getItem(storageKey) || null;
});
_.forEach(_.keys(cookieCache), function(cookieKey){
cookieCache[cookieKey] = cy.getCookie(cookieKey) || null;
});
});
Cypress.Commands.add('loadBrowserSession', function(options = {}){
_.forEach(_.keys(localStorageCache), function(storageKey){
if (typeof localStorageCache[storageKey] === 'string'){
localStorage.setItem(storageKey, localStorageCache[storageKey]);
}
});
_.forEach(_.keys(cookieCache), function(cookieKey){
if (typeof cookieCache[cookieKey] === 'string'){
cy.setCookie(cookieKey, cookieCache[cookieKey]);
}
});
});
Cypress.Commands.add('clearBrowserSession', function(options = {}){
_.forEach(_.keys(localStorageCache), function(storageKey){
localStorageCache[storageKey] = null;
});
_.forEach(_.keys(cookieCache), function(cookieKey){
cookieCache[cookieKey] = null;
});
cy.loadBrowserSession();
});
在测试中:
before(function(){
cy.clearBrowserSession();
});
beforeEach(function(){
cy.loadBrowserSession();
});
afterEach(function(){
cy.saveBrowserSession();
});
after(function(){
// Probably unnecessary as Cypress cleans up between tests.
cy.clearBrowserSession();
});
赛普拉斯Bug URL:https://github.com/cypress-io/cypress/issues/747
赛普拉斯UI测试的良好做法:Cypress good practices
答案 2 :(得分:0)
我做对了,只需要在下面的实际代码中添加
cy.request('/Account/SignIn')
.its('body')
.then((body) => {
const csrf = Cypress.$(body).find('input[name=__RequestVerificationToken]').val()
cy.login(myusername,mypassword,csrf) /* This custom method is defined in support/command.js */
.then((resp) => {
expect(resp.status).to.eq(200)
})
})