简体   繁体   English

使用 Renderer2 对 angular 组件进行单元测试

[英]Unit Testing angular component with Renderer2

I have a angular component which looks like this:我有一个 angular 组件,如下所示:

constructor(
        @Inject(INJECTION_TOKEN_WINDOW) private window: Window,
        private renderer: Renderer2
){}

ngOnInit() {
  this.renderer.addClass(this.window.document.body, 'myCssClass');
}

Unit test snippet:单元测试片段:

const TOKEN_WINDOW = 'Window';

const WindowMock = {
    document: {
        body: {}
    }
};
describe('MyComponent', () => {
let renderer: Renderer2;
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;

beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [MyComponent],
            schemas: [CUSTOM_ELEMENTS_SCHEMA],
            providers: [
                Renderer2,
                { provide: TOKEN_WINDOW, useValue: WindowMock }
            ]
        }).compileComponents();
    }));

beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        el = fixture.debugElement;

        renderer = fixture.componentRef.injector.get<Renderer2>(Renderer2 as Type<Renderer2>);
        spyOn(renderer, 'myCssClass').and.callThrough();
        fixture.detectChanges();
    });
})

//Tests here...

I am getting below error when I run the tests (for any test I am getting the same error below).我在运行测试时遇到以下错误(对于任何测试,我在下面遇到相同的错误)。 I guess something wrong with Renderer2 configuration in my test?我猜我的测试中 Renderer2 配置有问题? Please help请帮忙

TypeError: Cannot read property 'add' of undefined
    at <Jasmine>
    at DefaultDomRenderer2.push../node_modules/@angular/platform-browser/fesm5/platform-browser.js.DefaultDomRenderer2.addClass (http://localhost:9876/_karma_webpack_/node_modules/@angular/platform-browser/fesm5/platform-browser.js:1160:67)
    at DebugRenderer2.push../node_modules/@angular/core/fesm5/core.js.DebugRenderer2.addClass (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm5/core.js:30455:1)
    at <Jasmine>

I am thinking the Renderer2 requires the actual implementation of the window and not the mock and to mock the actual window to the point that the actual Renderer2 is satisfied can be cumbersome.我认为Renderer2需要 window 的实际实现而不是模拟,并且模拟实际的 window 到满足实际Renderer2的程度可能很麻烦。

Either mock both the window and Renderer2 to the point that your component is satisfied or provide the actual window and actual Renderer2 .模拟windowRenderer2到您的组件满意的程度,或者提供实际的 window 和实际的Renderer2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM