2

I have a "Messages" injectable that represents a service that can fetch a user's messages. This class depends on a "Database" class that logs in to the backend using the credentials of the user.

Now I want to write a test case during which 2 users are logged in at the same time, in order to test automatically whether messages sent from user 1 arrive directly at the inbox of user 2.

Therefore, I need a way to inject two different instances of "Messages" with two different, corresponding instances of "Database".

I tried the following:

  beforeEachProviders(() => [
    Messages, Database
  ]);

  beforeEach(inject([Messages], (msg) => {
    this.msg1 = msg;
  }));

  beforeEach(inject([Messages], (msg) => {
    this.msg2 = msg;
  }));

However, it turns out that msg1 and msg2 represent the same instance of "Messages":

it('testcase', () => {
  // this.msg1 == this.msg2;
});

Is it possible to tell the injector to create different instances of "Messages" and its dependencies?

1 Answer 1

1

This is how Angular DI works. For a single provider you always get the same instance.

As a workaround you could inject Injector and use

var child = ReflectiveInjector.fromResolvedProviders(
  ResolvedReflectiveProvider([Message, Database]), injector);
var msg2 = child.get(Message);

This way you should get a different instance of Message and Database while other providers are reused from the parent injector (like MockBackend, ...)`

You can also use

var injector = ReflectiveInjector.resolveAndCreate([Message, Database]);
var msg2 = child.get(Message);

But this way you need to provide all dependencies, not only Message and Database because there is no parent.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer, but I get this error: pastebin.com/raw/56N7sfZ9 I used this code: pastebin.com/raw/5kh2ZHvD
sorry, hit enter too early: I get this error: pastebin.com/raw/56N7sfZ9 I used this code: pastebin.com/raw/5kh2ZHvD
I got it wrong how to create child injectors. I updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.