I want to test the 'canViewPage method in jest. How do mock the const userPages which is the values from the func getUserPage
canViewPage(page){
const userPages = getUsersPages();
if(userPages.includes(page)){
return true;
}
return false;
}
getUsersPages(){
// here i hardcode a list of pages, for simplicity purposes
const pages = ['home','about','contact'];
return pages
}
here is what i tried
test('test canViewPage', () => {
const spy = jest.spyOn(canViewPage, 'userPages');
spy.mockReturnValue(['home','about','contact']);
expect(canViewPage('premiumPage')).toBe(false);
spy.mockRestore();
});
I also tried this
test('test canViewPage', () => {
const spy = jest.spyOn(canViewPage, 'getUsersPage');
spy.mockReturnValue(['home','about','contact']);
expect(canViewPage('premiumPage')).toBe(false);
spy.mockRestore();
});
getUsersPage()
, but you setting up the mock/spy incorrectly.getUsersPages()
is not defined/exported from withincanViewPage()
. Instead try targetinggetUsersPage()
directly to create a mock/spy. With the spy working, then you can assertcanViewPage('premiumPage')
accordingly. – DiazoniumgetUsersPage()
, is it can exported function? What have you tried from jestjs.io/docs/en/mock-functions other than what you shared in your question? – Diazonium