【问题标题】:Angular 2 testing a component with fake dependenciesAngular 2 测试具有虚假依赖项的组件
【发布时间】:2026-01-19 09:20:06
【问题描述】:

我正在尝试使用虚假依赖项测试 Angular 2 组件。

事实上,我正在使用 Ng2 和 Redux 构建一个简单的 TODO 应用程序,并且在我的一个组件中,我有一个 redux 应用商店的实例。

我需要模拟这个对象并监视它的 subscribe 方法。这样,我就有了一个如下所示的解决方案:

import { TestComponentBuilder } from '@angular/compiler/testing';
import {HomeComponent} from './home.component';
import {provide} from '@angular/core';
import {
    it,
    expect,
    inject,
    describe,
    async,
    beforeEachProviders
} from '@angular/core/testing';


class MockAppStore {

    title: String;
    constructor() {
        this.title = 'plouf';
    }
    subscribe(callback) {
        callback();
    }
}

describe('HomeComponent', () => {

    beforeEachProviders(() => [
        provide('AppStore', { useValue: MockAppStore })
    ]);

    it('should call the dispatch method of the appStore', async(inject([TestComponentBuilder],
        (tsb: TestComponentBuilder) => {
            tsb.createAsync(HomeComponent).then((fixture) => {
                // Given
                const component = fixture.componentInstance;
                spyOn(component.appStore, 'subscribe');

                // When
                fixture.detectChanges();

                // then
                expect(component.appStore.subscribe).toHaveBeenCalled();
            });
        })));
});

这应该测试以下组件:

import {Component, Inject} from '@angular/core';

@Component({
    selector: 'as-home',
    templateUrl: 'app/home/home.html',
    styleUrls: [
        'app/home/home.css'
    ]
})
export class HomeComponent {

    appStore: any;
    constructor( @Inject('AppStore') appStore: any) {
        this.appStore = appStore;
        this.appStore.subscribe(state => {
            console.log(state);
        });
    }
}

我的问题是测试根本没有通过,堆栈跟踪也不那么明确:

PhantomJS 2.1.1 (Windows 8 0.0.0) HomeComponent should call the dispatch method of the appStore FAILED
        invoke@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:323:34
        run@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:216:50
        C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:571:61
        invokeTask@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:356:43
        runTask@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:256:58
        drainMicroTaskQueue@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:474:43
        invoke@C:/Project/angular2/kanboard/node_modules/zone.js/dist/zone.js:426:41
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 16 of 16 (1 FAILED) (0.48 secs / 0.518 secs)
Remapping coverage to TypeScript format...
Test Done with exit code: 1
[08:28:55] 'unit-test' errored after 7.27 s
[08:28:55] Error: 1
    at formatError (C:\Project\angular2\kanboard\node_modules\gulp\bin\gulp.js:169:10)
    at Gulp.<anonymous> (C:\Project\angular2\kanboard\node_modules\gulp\bin\gulp.js:195:15)
    at emitOne (events.js:77:13)
    at Gulp.emit (events.js:169:7)
    at Gulp.Orchestrator._emitTaskDone (C:\Project\angular2\kanboard\node_modules\gulp\node_modules\orchestrator\index.js:264:8)
    at C:\Project\angular2\kanboard\node_modules\gulp\node_modules\orchestrator\index.js:275:23
    at finish (C:\Project\angular2\kanboard\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:21:8)
    at cb (C:\Project\angular2\kanboard\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:29:3)
    at DestroyableTransform.<anonymous> (C:\Project\angular2\kanboard\tasks\test.js:62:13)
    at emitNone (events.js:72:20)
    at DestroyableTransform.emit (events.js:166:7)
    at finishMaybe (C:\Project\angular2\kanboard\node_modules\remap-istanbul\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:475:14)
    at endWritable (C:\Project\angular2\kanboard\node_modules\remap-istanbul\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:485:3)
    at DestroyableTransform.Writable.end (C:\Project\angular2\kanboard\node_modules\remap-istanbul\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:455:41)
    at DestroyableTransform.onend (C:\Project\angular2\kanboard\node_modules\gulp\node_modules\vinyl-fs\node_modules\through2\node_modules\readable-stream\lib\_stream_readable.js:523:10)
    at DestroyableTransform.g (events.js:260:16)
    at emitNone (events.js:72:20)
    at DestroyableTransform.emit (events.js:166:7)
    at C:\Project\angular2\kanboard\node_modules\gulp\node_modules\vinyl-fs\node_modules\through2\node_modules\readable-stream\lib\_stream_readable.js:965:16
    at nextTickCallbackWith0Args (node.js:420:9)
    at process._tickCallback (node.js:349:13)
Remapping done! View the result in report/remap/html-report
npm ERR! Test failed.  See above for more details.

知道测试失败的原因吗?

否则,如果有人有想法,我正在寻找有关模拟 rxjs 可观察/订阅的良好做法。

感谢您的帮助

【问题讨论】:

    标签: javascript unit-testing typescript angular jasmine


    【解决方案1】:

    我认为问题出在您的预料之中。您可以尝试以下方法:

    expect(component.appStore.subscribe).toHaveBeenCalled();
    

    代替:

    expect(component.appStore).toHaveBeenCalled();
    

    【讨论】:

    • 感谢您的回答。但问题不在这里:(
    • 好的,我解决了这个问题。看来我为我的模拟类做了一个useValue...模拟应该是一个函数。
    最近更新 更多