I have react app testing with cypress. I am trying to create custom login command to use it throughout the testing.
The issue is that cy.request('POST', '/api/admin/user/register', {userInfo})
creates actual data in database which I absolutely don't want.
another issue is that 'login' button does not change to 'logout'. On the test, request returns 200, token exist in localStorage. I guess 'isLoggedIn' state (which is saved in redux storage on login success) need to be set in cypress.
How can I work around ?
commands.js
Cypress.Commands.add('login', userType => {
const types = {
admin: {
username,
companyName,
password,
contactNo,
bankAccountId,
email,
mealPrice,
businessType,
admin: true,
},
user: {
username,
companyName,
password,
contactNo,
bankAccountId,
email,
mealPrice,
businessType,
admin: false,
},
};
const userInfo = types[userType];
return cy
.request('POST', '/api/admin/user/register', { userInfo })
.then(()=>{
cy.route({
url: '/api/auth/login',
method: 'POST',
body: {
username: userInfo.username,
password: userInfo.password,
},
}).then(({ body }) => window.localStorage.setItem('token', body.token));
})
});
user.spec.js
describe('user', () => {
beforeEach(() => {});
it('can visit the app', () => {
cy.login('user').then(() => {
expect(window.localStorage.getItem('token')).to.exist;
cy.visit('/');
cy.contains('๋ก๊ทธ์์');
});
});
});
navBar.js
const Navbar = ({ isLoggedIn, handleUserLogout }) => (
<div className="flex justify-between">
{/* calling isLoggedIn() directly from localStoragy does not re-render the component on router history change. */}
{isLoggedIn ? (
<button
type="button"
className="nav--login-btn td-none c-text br f-mini"
onClick={handleUserLogout}
>
logout
</button>
) : (
<Link className="nav--login-btn td-none c-text br f-mini" to="/login">
login
</Link>
)}
</div>
);