0
我想測試一個服務,該服務調用一個真實的後端url並找不到解決方案。我的服務必須從服務器調用數據,並且我想確保數據來自服務,服務處理正確。角度爲真實後端的測試服務
因此,這裏是我的登錄服務的只是一個簡單的例子:
@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("[email protected]", "123456");
let loggedIn = loginService.loggedIn();
expect(loggedIn).toBe(true);
});
});
,但我得到以下錯誤: 類型錯誤:無法讀取屬性'登錄'未定義,所以服務必須是未定義的。我可以嘲笑這項服務,但我想用我在後端服務器上的真實數據庫來處理它。
那麼可能是什麼問題,我該如何解決它?
親切的問候,
安德烈
也許你忘了導入'HttpModule'到測試模塊? –