您是否知道如何为此类代码创建良好的测试:
login(login, password) {
console.log('login is called');
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let data = JSON.stringify({
username: login,
password: password
});
var $self = this;
this.http.post(
'http://localhost:8080/auth',
data,
{ headers }
).toPromise()
.then(function(response){
console.log('Then is resolved');
$self.setUserId(result.id);
$self.router.navigate([ '' ]);
});
}
我想检查一下:
getUserId()
之前,login(login, password)
应该是未定义的login(login, password)
时,我应该在控制台中看到然后被调用(在控制台中应该被称为console.log('then is called')
)getUserId()
之后login(login, password)
应该返回数值,因为那时的结果应该是一个对象{id: XXX, token: YYY}
我准备了规格,但我从未在then
结果中看到login
:
beforeEach( () => {
TestBed.configureTestingModule({
imports: [
HttpModule,
RouterTestingModule
],
providers: [
{ provide: XHRBackend, useClass: MockBackend },
UserService
]
});
});
beforeEach(inject([UserService, XHRBackend, Router], (_userService, mockBackend) => {
userService = _userService;
}));
describe('Login', () => {
it('user is not login', () => {
expect(userService.loggedIn).toBe(false);
});
it('login with good data',async(() => {
let login = "admin";
let pass = "admin";
expect(userService.getUserId()).not.toBeDefined();
let res = {
token: 'testtest',
id: '1'
};
userService.login(login, pass);
userService.whenStable().then(() => {
userService.login(login, pass);
expect(userService.getUserId()).toBeDefined();
});
}));
});