How to write jasmine test case for the following class having constructor which is having dependency on http
import {Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
@Injectable()
export class MockUserService {
items:Array<any>;
constructor(http:Http){
http.get('http://127.0.0.1:8080/src/data/names.json')
.subscribe(res => {
this.items = res;
console.log('results found');
})
}
}
I tried in following way ,
it('Testing user login', inject([MockUserService,Http], (mockUserService:MockUserService ) => {
let http:Http;
let mockUserService: MockUserService = new MockUserService(http);
expect(1+1).toEqual(2);
});
);
I am getting DI error: DI error Image
SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.
To test a service, you set the providers metadata property with an array of the services that you'll test or mock. content_copy let service: ValueService; beforeEach(() => { TestBed. configureTestingModule({ providers: [ValueService] }); }); Then inject it inside a test by calling TestBed.
For click event we can use triggerEventHandler method of Angular DebugElement class. We can also call native JavaScript click method of button. On click of button, we call a component method and it is possible that our component method has other dependencies to execute.
Assert is the phase where the code behavior is checked and verified. For example, the actual output is compared to the expected output.
This test
https://github.com/angular/angular/blob/master/modules/angular2/test/http/http_spec.ts#L104
uses return new Http(backend, defaultOptions);
where backend
is a MockBackend
(import {MockBackend, MockConnection} from 'angular2/src/http/backends/mock_backend';
You can use beforeEachProviders to DI easily like below:
beforeEachProviders(() => [
HTTP_PROVIDERS,
MockUserService
]);
describe('MockUser Service', () => {
it('Testing user login',
inject([MockUserService], (service: MockUserService) => {
expect(1 + 1).toEqual(2);
}));
});
I hope this will help you(of at least 6 months ago).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With