-
-
Notifications
You must be signed in to change notification settings - Fork 4.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Testing a service #130
Comments
Seems related to #124.
This should have been fixed by selecting the correct |
For me it works in the following way: // app.spec.ts
describe('App', () => {
// provide our implementations or mocks to the dependency injector
beforeEachProviders(() => [
App,
InstrumentFactory,
BaseRequestOptions,
MockBackend,
provide(Http, {useFactory:
function(backend, defaultOptions) {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]})
]);
it('should have an instrument', inject([InstrumentFactory], (instrumentFactory => {
var instrument = instrumentFactory.create({"id" : 7});
expect(instrument).not.toBeUndefined();
})));
}); // InstrumentFactory.ts
import {Injectable} from 'angular2/angular2';
import {Http} from 'angular2/http';
//import {Instrument} from "../Models/Instrument"; // you would use this import instead of the Instrument class below
/* Simple class for testing purposes only */
class Instrument {
private name: string;
public constructor(options: {id: number}) {
this.name = 'MyInstrument';
}
}
@Injectable()
export class InstrumentFactory {
private http : Http;
public constructor(http : Http) {
this.http = http;
}
public create(instrument:any): Instrument {
console.log(this.http); // just to demonstrate in the test, that the mocked HTTP backend is available via dependency injection
return new Instrument(instrument);
}
} So the trick is not to manually inject HTTP into the Why is this better? Think of a large app with hundreds of possible injections. What you want to do is tell the injector what should be used whenever a dependency is requested (e.g. use a mocked version of the HTTP service, etc.). Then whenever the injector resolves a dependency it chooses whatever you have defined. This makes it much easier than resolving the dependencies by hand, which is what you have tried in your approach. So please give it a try if it does work in this way. I have added a demo on my fork of this project. |
I'm adding this to the readme so I'll close this |
Hello,
We've been trying to test a service which depends on the angular HTTP service but we can't seem to get this to work properly.
My code is as follows:
app.spec.ts:
InstrumentFactory.ts:
I am getting the folowing error:
I know that phantomjs is not defined, but that should not really matter to this error.
The text was updated successfully, but these errors were encountered: