我想开玩笑地测试'canViewPage方法。 如何模拟const userPages,这是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
}
这是我尝试过的
test('test canViewPage', () => {
const spy = jest.spyOn(canViewPage, 'userPages');
spy.mockReturnValue(['home','about','contact']);
expect(canViewPage('premiumPage')).toBe(false);
spy.mockRestore();
});
我也尝试过
test('test canViewPage', () => {
const spy = jest.spyOn(canViewPage, 'getUsersPage');
spy.mockReturnValue(['home','about','contact']);
expect(canViewPage('premiumPage')).toBe(false);
spy.mockRestore();
});
答案 0 :(得分:0)
要模拟userPages
的值,您必须模拟getUserPage
。为此,取决于getUserPage
和canViewPage
的定义位置和定义方式。我假设这两个函数在类MyAwesomeClass
// MyAwesomeClass.js
export default class MyAwesomeClass {
canViewPage(page) {
const userPages = this.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;
}
}
// test.js
import MyAwesomeClass from '<path to MyAwesomeClass.js>'
test('test canViewPage', () => {
const instance = new MyAwesomeClass()
const spy = jest.spyOn(instance, 'getUsersPages');
spy.mockReturnValue(['mockItem1','mockItem2','mockItem3']);
expect(instance.canViewPage('premiumPage')).toBe(false);
expect(instance.canViewPage('mockItem1')).toBe(true);
spy.mockRestore();
});
如果canViewPage
和getUsersPages
是类中的静态方法,则模拟方式会不同
test('test canViewPage', () => {
const spy = jest.spyOn(MyAwesomeClass, 'getUsersPages');
spy.mockReturnValue(['mockItem1','mockItem2','mockItem3']);
expect(MyAwesomeClass.canViewPage('premiumPage')).toBe(false);
expect(MyAwesomeClass.canViewPage('mockItem3')).toBe(true);
spy.mockRestore();
});
答案 1 :(得分:0)
建议使用间谍和存根,但是如果您要访问外部作用域对象,可以修改窗口变量并为其分配所需的值
例如:
var a = 10;
const myfun = () => {
return a + 20;
}
test('myfun', () => {
window.a = 20
expect(myfun).toBe(40)
}