Skip to content

Add getInstanceWithProviders() utility for testing services with dependencies #528

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

Paratron
Copy link

@Paratron Paratron commented Jun 2, 2025

I am currently introducing testing-library for angular with vitest at our company and learned that while there is the very handy render() function in testing-library, an alternative for testing services or facades with injections did not exist.

I added a small new function getInstanceWithProviders() to the library which simplifies dependency injections into services or facades.

Example

@Injectable()
class DatabaseService {
  getData() {
    return 'real data';
  }
}

@Injectable()
class UserService {
  private db = inject(DatabaseService);

  getUser() {
    return `User: ${this.db.getData()}`;
  }
}

// Test with mocked dependency
it('should inject a mock service into a service that depends on it', () => {
  const mockDatabase = { getData: () => 'mock data' };
  
  const userService = getInstanceWithProviders(UserService, [
    { provide: DatabaseService, useValue: mockDatabase }
  ]);

  expect(userService.getUser()).toBe('User: mock data');
});

I have already created a test file for the new function and can also provide an example in the example project if this addition to the library is desired.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant