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
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions projects/testing-library/src/lib/testing-library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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?

TestBed.configureTestingModule({
providers: [serviceClass, ...providers],
});

return TestBed.inject(serviceClass);
}

export async function render<ComponentType>(
component: Type<ComponentType>,
renderOptions?: RenderComponentOptions<ComponentType>,
Expand Down
28 changes: 28 additions & 0 deletions projects/testing-library/tests/getInstanceWithProviders.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Injectable } from '@angular/core';
import { getInstanceWithProviders } from '../src/lib/testing-library';

describe('getInstanceWithProviders', () => {
@Injectable()
class DatabaseService {
getData() {
return 'real data';
}
}

@Injectable()
class UserService {
constructor(private db: DatabaseService) {}

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

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');
});
});