Recently, I delved into the world of Cypress testing and came across a code snippet from an official documentation recipe that I slightly modified:
let token: string;
function fetchUser() {
cy.request('POST', 'https://my-api/', {
email: Cypress.env("USER_LOGIN"),
password: Cypress.env("USER_PASSWORD"),
})
.its('body')
.then((res) => {
token = res.token;
});
}
function setUser() {
cy.visit('/projects', {
onBeforeLoad(win) {
win.localStorage.setItem('token', JSON.stringify({ token }));
for (let i = 0; i < 5; i++) {
win.localStorage.setItem(`guidedTour${i}`, 'true');
}
},
});
}
before(fetchUser);
beforeEach(setUser);
it('my test', () => {
// some testing happens here
});
The current setup works fine, but I want to refactor fetchUser
and setUser
into a separate file to avoid redundancy in new test files. However, when I move them to a new file, fetchUser
correctly sets the token
value, while setUser
receives undefined
. As a TypeScript beginner with limited experience in handling asynchronous functions, I'm a bit lost. Here's my attempted solution:
authentication.js
export function fetchUser(token: string): string {
console.log('fetchUser line 1 ' + token);
cy.request('POST', 'https://my-api', {
email: Cypress.env("USER_LOGIN"),
password: Cypress.env("USER_PASSWORD"),
})
.its('body')
.then((res) => {
token = res.token;
return token;
});
}
export function setUser(token: string) {
cy.visit('/projects', {
onBeforeLoad(win) {
win.localStorage.setItem('token', JSON.stringify({ token }));
for (let i = 0; i < 5; i++) {
win.localStorage.setItem(`guidedTour${i}`, 'true');
}
},
});
}
Main Test File
import { fetchUser, setUser } from "../support/authentication";
let token: string;
before(() => {
token = fetchUser(token);
});
beforeEach(() => {
setUser(token);
});
it('my test', () => {
// Testing scenarios go here
});
Any advice on how to resolve this issue would be greatly appreciated.