测试中的RendererFactory2失败

时间:2018-03-29 14:15:02

标签: angular jasmine

我在角度5应用程序中有一个首选项服务,它从本地存储加载'light-theme''dark-theme'并相应地向主体添加一个类。

import {Injectable, OnDestroy, Renderer2, RendererFactory2} from '@angular/core';
// ...

@Injectable()
@AutoUnsubscribe()
export class UiPreferencesService implements OnDestroy {

private renderer: Renderer2;

    constructor(rendererFactory: RendererFactory2) {
        this.renderer = rendererFactory.createRenderer(null, null);
        this.loadPrefs();
    }
  // moar code
    private emitTheme(theme) {
        this.currentThemeSubject.next(theme);
        this.renderer.addClass(document.body, theme);
        this.renderer.removeClass(document.body, this.notCurrentTheme());
    }
}

我必须使用RendererFactory2,因为我在我的服务中使用了渲染器。我遇到的问题是在我的测试中:

Cannot call addClass on null

如何让RendererFactory2在我的测试中运行。

2 个答案:

答案 0 :(得分:0)

创建一个实现RendererFactory2的模拟类。在您的service.spec.ts

中实例化它

答案 1 :(得分:0)

在您的提供程序中,您需要模拟RendererFactory2并将设置渲染器设置为接收匿名函数:

mockProvider(RendererFactory2, {
     createRenderer: () => renderer2
}),

renderer2应该具有您需要的功能:

let renderer2: Renderer2 = {
        addClass: jasmine.createSpy('addClass'),
        removeClass: jasmine.createSpy('removeClass'),
    } as unknown as Renderer2;

然后,在测试中使用renderer2:

expect(renderer2.addClass).toHaveBeenCalledWith(document.body, 'your-class');

是这样的:

describe('Some name', () => {
    let renderer2: Renderer2 = {
        addClass: jasmine.createSpy('addClass'),
        removeClass: jasmine.createSpy('removeClass'),
    } as unknown as Renderer2;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [],
            providers: [
                ...your providers...,
                mockProvider(RendererFactory2, {
                    createRenderer: () => renderer2
                }),
            ],
        }).compileComponents();
    }));

    describe('adding a class to body', () => {
        it('renderer addClass should be called', () => {
            //your code which triggers class adding
            expect(renderer2.addClass).toHaveBeenCalledWith(document.body, 'your-class');
        });