Я новичок, использующий Angular9 и Firebase. Я следую учебному пособию, в котором преподаю Angular9, Firebase и TDD суду Карма Жасмин. На самом деле у меня тест не пройден из-за того, что Json объект возврата из вызова http firebase возвращает пустой json. Я попытался вызвать этот URL через браузер, и он работает, браузер возвращает Json правильно.
Это ошибка Karma Jasmine:
CartService > should have callHttp woeking
SyntaxError: Unexpected end of JSON input
at <Jasmine>
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/services/cart/cart.service.spec.ts:111:32)
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:1749:1)
at TestBedRender3.execute (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:3137:1)
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:4299:22)
at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)
at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:292:1)
at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:363:1)
at Zone.run (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:123:1)
at runInTestZone (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:545:1)
Затрагиваемый класс: --cart.service .spe c .ts -
import { TestBed, inject, fakeAsync, tick } from '@angular/core/testing';
import { CartService } from './cart.service';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestore, AngularFirestoreModule } from '@angular/fire/firestore';
import { CartList } from './cart.services.mock';
import { Observable } from 'rxjs';
import { MockBackend } from '@angular/http/testing';
import { Http, ConnectionBackend, BaseRequestOptions, Response } from '@angular/http';
import { httpFactory } from '@angular/http/src/http_module';
import { JsonPipe } from '@angular/common';
export const environment = {
production: false,
firebase: {
apiKey: "AIzaSyDNW48hAmvH8eAZpbeflRKb0khY5Blzsqg",
authDomain: "angularfirebasegb.firebaseapp.com",
databaseURL: "https://angularfirebasegb.firebaseio.com",
projectId: "angularfirebasegb",
storageBucket: "angularfirebasegb.appspot.com",
messagingSenderId: "388340512107",
appId: "1:388340512107:web:2cf5e9a1daea5cfaf1082e",
measurementId: "G-L43R4QN2LN"
}
};
let AngularFireStoreMock = {
collection: function (param: any) {
return {
// mime valueChanges in cart.service.ts
valueChanges: function () { return Observable.of(CartList) },
add: function (item) { return item }
}
}
}
describe('CartService', () => {
let service: CartService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule
],
providers: [
CartService,
{ provide: AngularFirestore, useValue: AngularFireStoreMock },
BaseRequestOptions,
MockBackend,
{
provide: Http,
useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
},
// dependencies
deps: [MockBackend, BaseRequestOptions]
}
]
});
service = TestBed.inject(CartService);
});
it('should have callHttp woeking', inject([CartService, MockBackend], fakeAsync((service: CartService, backend: MockBackend) => {
let responseFromBackEnd;
let response =
{
"documents": [
{
"name": "projects/angularfirebasegb/databases/(default)/documents/cart/dhnV5jYUPDTOUZyfGDw1",
"fields": {
"genre": {
"mapValue": {}
},
"category": {
"stringValue": ""
},
"price": {
"doubleValue": 100.1
},
"title": {
"stringValue": "Hello world"
},
"description": {
"stringValue": "Hello world description"
},
"image": {
"stringValue": "https://image.shutterstock.com/image-photo/white-transparent-leaf-on-mirror-260nw-1029171697.jpg"
},
"upvotes": {
"integerValue": "0"
}
},
"createTime": "2020-05-03T23:03:37.329754Z",
"updateTime": "2020-05-03T23:09:04.281872Z"
}
]
};
backend.connections.subscribe(connection => {
connection.mockRespond(new Response(<any>{
body: JSON.stringify(Response)
}));
});
service.httpCall().subscribe(data => {
responseFromBackEnd = data;
});
tick();
let jsonFromBackend = JSON.parse(responseFromBackEnd.text());
expect(jsonFromBackend).toEqual(response);
}))
);
it('should be created', inject([CartService], (service: CartService) => {
expect(service).toBeTruthy();
}));
it('should have add method defined', inject([CartService], (service: CartService) => {
expect(service.add).toBeTruthy();
}));
it('should have query method defined', inject([CartService], (service: CartService) => {
expect(service.query).toBeTruthy();
}));
it('should have query method defined working', inject([CartService], fakeAsync((service: CartService) => {
let all$ = service.query();
let response;
// NOMINARE LE VARIABILI DI TIPO OBSERVABLE CON IL '$', PER CONVENZIONE. TUTTAVIA NON E' OBBLIGATORIO
all$.subscribe((items) => {
response = items;
});
// use tick because is an asyncronous call, thus go ahed and do all the necesary changes
tick();
expect(response).toBe(CartList);
})));
});
, как вы можете видеть, я вызываю тест под названием «должен быть callHttp woeking», исключение составляет:
let jsonFromBackend = JSON.parse(responseFromBackEnd.text());
из-за пусто Json. Json дается из:
service.httpCall().subscribe(data => {
responseFromBackEnd = data;
});
Метод httpCall () определен в:
- cart.service.ts -
import { Injectable } from '@angular/core';
// install rxjs first: npm install rxjs-compat --save
import { Observable } from 'rxjs/Observable';
import { BookModel } from '../../models/book/book.model';
import { Subject } from 'rxjs/Subject';
import { AngularFirestore } from '@angular/fire/firestore';
//import { AngularFirestore } from 'angularfire2/firestore';
// se non presente: npm install @angular/http@latest
import { Http } from '@angular/http';
@Injectable({
providedIn: 'root'
})
export class CartService {
private emitAddToCart = new Subject<any>();
addEmitted$ = this.emitAddToCart.asObservable();
// http requests (https://firebase.google.com/docs/firestore/use-rest-api) example of httprequest
hardCodeUrl = 'https://firestore.googleapis.com/v1/projects/angularfirebasegb/databases/(default)/documents/cart?key=AIzaSyDNW48hAmvH8eAZpbeflRKb0khY5Blzsqg';
constructor(private db: AngularFirestore, private http: Http) { }
query() {
// promise
return this.db.collection('/cart').valueChanges();
}
add(data){
// this is going to put some items into an item collection, storing data in firebase
let item = this.db.collection<BookModel>('/cart').add(data.getData());
// next is going to do all the save for us (but the name is a quite strange)
this.emitAddToCart.next(item);
return item;
}
emitChange(book: BookModel) {
this.emitAddToCart.next(book);
}
httpCall() {
return this.http.get(this.hardCodeUrl);
}
}
и environment.ts содержит мои настройки Firebase. На самом деле '' https://firestore.googleapis.com/v1/projects/angularfirebasegb/databases/ (по умолчанию) / documents / cart? Key = AIzaSyDNW48hAmvH8eAZpbeflRKb0khY5Blzsqg 'работает в браузере, возвращает объект json, но в моем коде
не работает