在 Angular2 组件的测试中,我在为 RouteParams 依赖项注入模拟时遇到了一些麻烦。我的一般想法是我可能会错过一些提供者。
测试失败:
无法解析“RouteParams”(?)的所有参数。确保所有参数都用 Inject 修饰 或具有有效的类型注释,并且“RouteParams”用 Injectable 装饰。
有谁知道问题可能是什么?
import {
it,
inject,
injectAsync,
describe,
beforeEach,
beforeEachProviders,
TestComponentBuilder
} from 'angular2/testing';
import {Component, provide} from 'angular2/core';
import {BaseRequestOptions, Http} from 'angular2/http';
import {MockBackend} from 'angular2/http/testing';
import {RouteParams, ROUTER_PROVIDERS, ROUTER_PRIMARY_COMPONENT} from 'angular2/router';
// Load the implementations that should be tested
import {Home} from './home';
import {Title} from './providers/title';
describe('Home', () => {
// provide our implementations or mocks to the dependency injector
beforeEachProviders(() => [
Title,
Home,
provide(RouteParams, { useValue: new RouteParams({ id: '1' }) }),
BaseRequestOptions,
MockBackend,
provide(Http, {
useFactory: function(backend, defaultOptions) {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
}),
provide(RouteParams, {
useFactory: function() {
return new RouteParams({ 'id':'1' });
}
})
]);
it('should have a title', inject([ Home ], (home) => {
expect(home.title.value).toEqual('Angular 2');
}));
it('should have a http', inject([ Home ], (home) => {
expect(!!home.http).toEqual(true);
}));
it('should log ngOnInit', inject([ Home ], (home) => {
spyOn(console, 'log');
spyOn(console, 'info');
expect(console.log).not.toHaveBeenCalled();
expect(console.info).not.toHaveBeenCalled();
home.ngOnInit();
expect(console.log).toHaveBeenCalled();
expect(console.info).toHaveBeenCalledWith('1');
}));
});