Skip to content

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.

@@ -42,6 +42,14 @@ type SubscribedOutput<T> = readonly [key: keyof T, callback: (v: any) => void, s
const mountedFixtures = new Set<ComponentFixture<any>>();
const safeInject = TestBed.inject || TestBed.get;

export function getInstanceWithProviders<T>(serviceClass: Type<T>, providers: any[]): T {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello, thanks for raising the PR.

Personally, I don't see a lot of value of creating this function.
Having this function in your own codebase is totally fine, and also allows more flexibility to configure the testbed.

What would the main reason be in your opinion to have this available in Angular Testing Library?

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.

2 participants