我在 Angular 9 应用程序中有一个首选项服务,它创建一个脚本标签,它使用来自 Renderer2 的“createElement”。当我尝试模拟 Renderer2 时,无法识别 createElement。
这是我的 service.ts :
@Injectable()
export class MyServer {
private renderer: Renderer2;
constructor(
//....
rendererFactory: RendererFactory2) {
this.renderer = rendererFactory.createRenderer(null, null);
}
public createScript() {
if (isLoginPage) {
const script = this.renderer.createElement('script');
script.type = 'text/javascript';
script.src = 'urlScript';
this.renderer.appendChild(document.body, script);
}
}
}
这是我的 service.spec.ts : describe('MyServer', () => {
describe('creerScriptTag', () => {
beforeEach(() => TestBed.configureTestingModule({
declarations: [],
imports: [],
providers: [
MyServer,
ConfigurationService,
{ provide: ModelService, useClass: ModelMockService },
Renderer2
]
}
));
it('isLogin True verify that the script was created',
inject([ConfigurationService, MyServer],
(configurationService: ConfigurationService,
myServer: MyServer,
renderer2: Renderer2) => {
spyOn(configurationService, 'getConfig').and.returnValue('anyString');
myServer.createScript();
expect(renderer2.createElement).toHaveBeenCalledTimes(1);
})
);
});
当我运行测试时出现此错误TypeError: Cannot read property 'createElement' of undefined
请有任何想法,