I have read many questions here and a few tutorials and I still can't get this working, I've copied the tutorials word-for-word and still no luck so I have no idea what the issue is. I'm pretty new to this stuff. Here's my code:
import { TestBed, inject, async } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import {
BaseRequestOptions,
HttpModule,
Http,
Response,
ResponseOptions
} from '@angular/http';
import { ItemsService } from './items.service';
import { MOCKITEMS } from './mock-items';
describe('ItemsService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [ItemsService]
});
});
it('should construct', inject([ItemsService], (service) => {
expect(service).toBeDefined();
}));
});
describe('ItemsService Mock', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ItemsService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend, opts) => new Http(backend, opts),
deps: [MockBackend, BaseRequestOptions]
}
],
imports: [HttpModule]
});
});
it('should construct', inject([ItemsService, MockBackend], (service, mockBackend) => {
expect(service).toBeDefined();
}));
describe('#getItems()', () => {
it('should return <Array<Items>>', inject([ItemsService, MockBackend], (service, mockBackend) => {
const mockReponse = {
data: [
{ itemCharId: 1, itemName: 'milk' },
{ itemCharId: 2, itemName: 'eggs' },
{ itemCharId: 3, itemName: 'meat' }
]
}
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({ body: JSON.stringify(mockReponse) })));
});
service.getItems().subscribe((items) => {
expect(items.length).toBe(3);
expect(items[0].itemName).toEqual('milk');
expect(items[1].itemName).toEqual('eggs');
expect(items[2].itemName).toEqual('meat');
});
}));
});
});
The tests are failing with expected undefined to be 3, etc. So I'm assuming it's not actually getting my mockResonse obj as the response or something on those lines? Could just be something small too I guess.
Service code:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class ItemsService {
constructor(private http: Http) { }
getItems() {
return this.http.get('/api/items');
}
}
Any help greatly appreciated.
servicecode small. It's quite huge. Please, provide all relevant code. It's necessary to get an idea on what you're testing.