gpt4 book ai didi

angular - 如何在构造函数中使用渲染器测试组件

转载 作者:太空狗 更新时间:2023-10-29 17:28:59 25 4
gpt4 key购买 nike

考虑这段代码:

import {
Component,
OnInit,
Renderer,
OnDestroy
} from '@angular/core';

import { TranslateService } from 'ng2-translate/ng2-translate';

export class AppComponent implements OnInit, OnDestroy {

constructor( private translate: TranslateService, renderer: Renderer ) {
this.globalKeyListenFunc = renderer.listenGlobal('document', 'keydown', (event) => {
if (event.keyCode === 18) { // ALT-Key
event.preventDefault();
}
});
...
}

如何使用 jasmine 测试来测试这样的组件?

我尝试了以下测试:

describe('App', () => {
let injector: Injector;
let backend: MockBackend;
let connection: MockConnection;
let translate: TranslateService;
let renderer: Renderer;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule, TranslateModule.forRoot()],
providers: [
AppComponent,
{provide: XHRBackend, useClass: MockBackend},
Renderer
]
});
injector = getTestBed();
backend = injector.get(XHRBackend);
translate = injector.get(TranslateService);
renderer= injector.get(Renderer);
backend.connections.subscribe((c: MockConnection) => connection = c);

});


it('should have fore languages', inject([ AppComponent ], (app: AppComponent) => {
app.ngOnInit();
expect(app.supportedLanguages.length).toBe(4);
}));

我得到的错误:

TypeError: undefined is not a constructor (evaluating 'renderer.listenGlobal') in config/spec-bundle.js

Renderer 实例似乎与真实浏览器环境中的行为不同。与往常在 CI 环境中一样,我使用 PhantomJS 浏览器来执行测试。

最佳答案

这应该适用于 Angular 6+

在你的 component.spec.ts 中

let renderer2: Renderer2;
...
beforeEach(async( () => {
TestBed.configureTestingModule({
...
providers: [Renderer2]
}).compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(YourComponent);
// grab the renderer
renderer2 = fixture.componentRef.injector.get<Renderer2>(Renderer2 as Type<Renderer2>);
// and spy on it
spyOn(renderer2, 'addClass').and.callThrough();
// or replace
spyOn(renderer2, 'addClass').and.callFake(..);
// etc
});

it('should call renderer', () => {
expect(renderer2.addClass).toHaveBeenCalledWith(jasmine.any(Object), 'css-class');
});

关于angular - 如何在构造函数中使用渲染器测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40196265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com