mercredi 28 mars 2018

Get access to Angular service instance from JavaScript code

What I'm trying to do is have some testing assertions based on the data in the Angular service, i.e. we're trying to create E2E tests and the tool we're using allows us to execute arbitrary JavaScript code for assertions, so for that I need to know if it's possible to get access to the Angular service instance.

How can I get access to an Angular service instance from plain JS code?

That is, if my Angular app is deployed, and I open the app in the browser, then open Chrome DevTools, can I get access to the service instance of the my Angular service that was provided to all components?

I know it's possible to get access to your component by through ng.probe($0) etc. but not sure about services.

From what I have searched so far, it seems like we have to do use the Injector class and then use it's .get() method to get access to one of the Angular service instances but I'm not sure how would I get access to the Injector class/instance itself?

Here's what I tried: ng.probe($0) ($0 being the <app-root> of my app) and then I see that the return value has an .injector property, I tried to call ng.probe($0).injector.get('MyServiceName') and got an error for: Uncaught Error: No provider for MyServiceName!.

(Even though I'm trying ng.probe above, I would love to know how to get access to the injector without ng.probe because during testing execution, I don't think I'll be able to do ng.probe($0))

So I'm not sure if I'm trying to access it the right way? Any ideas?

I'm using Angular 4.

Aucun commentaire:

Enregistrer un commentaire