我对Angular2很新,所以请原谅,如果措辞不合适。
我正在为注入授权服务的登录组件创建单元测试。 Authorization服务在构造函数中使用http。因此,当我注入Authorization服务时,我需要在inject语句中包含一个实例化的http。我一直在撕扯我的声音,试图弄清楚我发现的所有例子都是用RC4-RC5编写的,而且不再有效。这是我的代码。
授权类:
@Injectable()
export class AuthenticationService {
private subject = new Subject<any>();
constructor(private http: Http) { }
login(username: string, password: string, rememberMe: boolean = false) {
return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
.map((response: Response) => {
/// A bunch of code
}
...
单元测试(Jasmine)
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let authService: any;
let http: Http;
authService = new AuthenticationService(http);
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ FormsModule, RouterTestingModule, HttpModule ],
declarations: [ LoginComponent ],
providers: [
fakeBackendProvider,
MockBackend,
BaseRequestOptions,
{provide: AuthenticationService, useValue: authService},
{
provide: Http,
useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
return new Http(backend, options);
}}
]
});
TestBed.compileComponents().then(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
}));
it('Should show error "Invalid Username and Password." when the username/password combination is not valid', () => {
component.user.username = 'test';
component.user.password = 'test';
component.login();
expect(component.errorMsg).toBe('Invalid Username and Password.');
});
我知道http必须实例化,但无论如何我无法找到在RC5之后工作的。此外,我已经创建了一个完整的http fakebackendprovider,我在演示没有后端的应用程序时使用,所以我更喜欢使用它。我只是想不通怎么做。
export let fakebackendprovider = {
provide: Http,
useFactory: fakeBackend,
deps: [MockBackend, BaseRequestOptions]
}