如何修复undefined不是一个对象(评估'newOptions.merge')?

时间:2017-02-07 23:52:47

标签: unit-testing angular

我正在写有角2应用程序。此测试由angular cli创建,默认情况下失败:

  it('should render title in a h1 tag', async(() => {
    let fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    let compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('app works!');
  }));

错误信息是:

  

失败:./AppComponent类错误AppComponent - 内联模板:51:14导致:undefined不是对象(评估'newOptions.merge')   mergeOptions @ webpack:///~/@angular/http/src/http.js:47:0< - src / test.ts:69434:22   get @ webpack:///~/@angular/http/src/http.js:147:0< - src / test.ts:69534:1010

我可以发现newOptions.merge来自mergeOptions内的node_modules/@angular/http/src/http.js方法。

为了让测试通过,我需要做些什么?

这是gist fro app.component.ts
她是gist for app.component.html

1 个答案:

答案 0 :(得分:1)

您正在使用Angular 2 Http服务,因此您需要注入 defaultOptions 参数,在您的情况下,这是空的。

使这项工作的最佳方案是在spec.ts文件中添加以下行:

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [{
                provide: Http,
                useFactory: (
                    backend: ConnectionBackend, 
                    defaultOptions: BaseRequestOptions
                ) => {
                    return new Http(backend, defaultOptions);
                },
                deps: [BaseRequestOptions]
            },
            {
                provide: BaseRequestOptions,
                useClass: BaseRequestOptions
            }
        ]
    });
});

因此,当您告诉提供者BaseRequestOption使用类BaseRequestOptions时,这一行至关重要。