1

我在 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

请有任何想法,

4

1 回答 1

1

我通过创建一个包含我需要它们的元素的 const 解决了这个问题,并且我监视 RendererFactory2 以返回我创建的 const:

// create the const
const render2 = {createElement: jasmine.createSpy('createElement'), appendChild: 
jasmine.createSpy('appendChild')};

//mock of RendererFactory2 return the const
beforeEach(() => {
  spyOn(TestBed.get(RendererFactory2), 'createRenderer').and.returnValue(render2);
}
);

// I use the render2 const as it's my Renderer2
expect(render2.appendChild).toHaveBeenCalled();
于 2020-09-25T15:14:42.990 回答