Angular 2 个测试依赖项

Angular 2 test dependencies

我正在尝试使用 Angular 2 测试组件,但在加载依赖项时遇到问题。

我在测试 UserShowcaseComponent 时尝试导入 UserModule 时遇到 Karma 错误,如果我不导入它,我会收到很多缺少组件的错误。

测试设置是 angular-cli 生成的,我的具体测试如下

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { UserModule } from '../../user.module';
import { UserShowcaseComponent } from './user-showcase.component';

describe('UserShowcaseComponent', () => {
    let component: UserShowcaseComponent;
    let fixture: ComponentFixture<UserShowcaseComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [UserModule],     <---------------------------------- NOTE
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(UserShowcaseComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});

Karma 的错误很简单(这是完整的输出,没有测试运行):

29 11 2016 16:49:40.478:INFO [karma]: Karma v1.2.0 server started at http://localhost:9876/
29 11 2016 16:49:40.479:INFO [launcher]: Launching browser Chrome with unlimited concurrency
29 11 2016 16:49:40.649:INFO [launcher]: Starting browser Chrome
29 11 2016 16:49:42.010:INFO [Chrome 53.0.2785 (Linux 0.0.0)]: Connected on socket /#Jpv1IioGnou6CQtUAAAA with id 98117142
Chrome 53.0.2785 (Linux 0.0.0) ERROR

问题是 Karma 没有加载供应商文件,而且没有正确报告。此报告问题已于 angular-cli 1.0.0-beta.20 得到修复,请参阅 this commit

解决方案是在 karma.conf.js 中添加供应商库,在我的例子中添加

{ pattern: './node_modules/jquery/dist/jquery.min.js', watched: false }

files

是的,我知道我不应该使用 jquery。