使用Jasmine测试时,调用index.html中引入的getSurvey方法报错如何解决?
问题原因与解决方案
你遇到的问题是因为Jasmine测试环境不会自动加载index.html中引入的全局脚本,所以测试时window.getSurvey这个函数不存在,导致报错。
解决方法很简单,在测试文件里手动模拟这个全局函数即可,有两种常见方式:
1. 模拟空函数(仅避免报错)
在测试的初始化阶段(比如beforeEach钩子),给window对象添加一个空的getSurvey函数:
beforeEach(() => { // 其他测试初始化代码(比如TestBed配置) (window as any).getSurvey = () => {}; });
2. 用Jasmine Spy模拟(可验证调用情况)
如果需要验证这个函数是否被正确调用,可以用Jasmine的Spy来创建模拟函数:
beforeEach(() => { // 其他测试初始化代码 (window as any).getSurvey = jasmine.createSpy('getSurvey'); }); // 在测试用例里添加断言 it('Access service getUser and calls getSurvey', fakeAsync(() => { const user = new ResponseAPI<User>({fakeUser}); spyHttp = spyOn(userService, 'getUser').and.returnValue(of(user)); component.enableNpsAndCsat(); tick(600); flush(); expect(spyHttp).toHaveBeenCalled(); // 验证getSurvey是否被调用,以及参数是否正确 expect((window as any).getSurvey).toHaveBeenCalledWith('tokenTeste', expect.any(Object)); }));
补充说明
测试环境是独立的沙箱环境,不会引入主应用index.html里的外部脚本或全局函数,所有依赖的全局变量/函数都需要手动模拟或注入,这是前端单元测试的常规操作。
内容的提问来源于stack exchange,提问作者Fernanda Guimaraes
相关产品推荐
相关产品推荐

