I recently started writing tests with Cypress and I use a slightly modified version of the code available in one of the official documentation's recipes:
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
});
It works fine. Now I would like to move fetchUser and setUser to a separate file to avoid duplicating them in each new test file. When I do that, fetchUser takes token and sets it to its intended value, but what setUser gets is undefined. I'm quite the beginner in TypeScript and I have never handled asynchronous functions before, and I'm kinda lost. Here's what I tried:
authentification.js
export function fetchUser(token: string): string { // Warning: "A function whose declared type is neither 'void' nor 'any' must return a value."
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/authentification";
let token: string;
before(() => {
token = fetchUser(token);
});
beforeEach(() => {
setUser(token);
});
it('my test', () => {
// I'd like some testing to still happen here
});
How can I make it work?