我想测试一个服务,它调用一个真正的后端网址,但无法找到它的解决方案。我的服务必须从服务器调用数据,我想确保数据来到服务,服务处理它。
所以这只是我登录服务的一个简单示例:
@Injectable()
export class LoginService {
/**
* The token, which will be stored on the localStorage.
*/
public token: string;
//Eventemitter, for updating the navigation, when the user logs in
@Output() loggedInEm:EventEmitter<any> = new EventEmitter();
constructor(private http: Http) {
// set token if saved in local storage
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser && currentUser.token;
}
login(_mail, _pass): Observable<number> {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var data = {
mail: _mail,
pass: _pass
};
return this.http.post('/login', JSON.stringify(data), {
headers : headers
}).map((response: Response) => {
let res = response.json();
this.logged = res;
});
}
public loggedIn() : boolean {
return this.logged;
}
这就是我想测试它的方式:
describe('Login Service', () => {
let loginService: LoginService;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
],
providers: [
LoginService
],
imports: [
FormsModule,
IonicModule
],
});
inject([LoginService], (service) => {
loginService = service;
});
});
it("Should login user", () => {
loginService.login("mail@mail.ru", "123456");
let loggedIn = loginService.loggedIn();
expect(loggedIn).toBe(true);
});
});
但我收到以下错误: TypeError:无法读取属性&#39; login&#39;未定义的,所以服务必须是未定义的。我可以模拟服务,但我想用我在后端服务器上的真实数据库来处理它。
那么问题是什么呢?我该如何解决?
亲切的问候,
的Andrej
答案 0 :(得分:0)
试试这个:
it("Should login user", () => {
loginService.login("mail@mail.ru", "123456").subscribe(value => {
let loggedIn = loginService.loggedIn();
expect(loggedIn).toBe(true);
done();
});
})