Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

What would be a proper way to test (standalone) services #248

Unanswered
the-ult asked this question in Q&A
Discussion options

Can we use the testing-library/angular for unit testing services as wel.
Like an AuthService.
So without creating a 'login-component' or something to render() and call the autService

Or in that case, just use 'plain' jest / Angular Testbed. Or even a separate library like https://ngneat.github.io/spectator/

The sample: https://github.com/testing-library/angular-testing-library/blob/main/apps/example-app/src/app/examples/12-service-component.spec.ts uses a Component to test/mock the service.

You must be logged in to vote

Replies: 2 comments 1 reply

Comment options

What is the advantage of this, and what would be the big difference of creating the service manually via its constructor?

You must be logged in to vote
0 replies
Comment options

For example. We are working on a little auth-library atm with keycloak integration.
There are no UI components in this lib. Like a login-form or something like that. These are handled by the Keycloak OIDC provider.
But there are services, which are keeping state, tokens, etc. And which has methods like login(), logout() etc.

What would be the best way to test them with (or without) testing-library. Since this might be hard(er)

The more your tests resemble the way your software is used,
the more confidence they can give you.

Or is this what you meant by:

creating the service manually via its constructor

In that case, the answer to the question "What would be a proper way to test (standalone) services" would be:
Use (default) Jest, without testing-library helpers. And just Inject / Or create the AuthService via it's constructor and setup/call the methods you need to test.

Correct?

You must be logged in to vote
1 reply
Comment options

Correct.
For most of the service tests that I've seen, you don't need to use the Angular TestBed or the Angular Testing Library..
You can create the service "manually" via its constructor.
There are a few exceptions when this is harder (e.g. when the service requires a lot of Angular services).

For your example, I would create a AuthService instance and provide a mock for the keycloak integration (if it's making network requests),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /