Skip to content

Instantly share code, notes, and snippets.

@LcsGa
Last active September 20, 2023 09:25
Show Gist options
  • Select an option

  • Save LcsGa/3aeabf3bdb8713ff92f62a6ac314cab0 to your computer and use it in GitHub Desktop.

Select an option

Save LcsGa/3aeabf3bdb8713ff92f62a6ac314cab0 to your computer and use it in GitHub Desktop.
@Injectable()
export class TestService {
public readonly number: number = 123;
}
@Component({
standalone: true,
providers: [TestService],
selector: 'pat-coucou',
template: '{{ number }}'
})
export class TestComponent {
public readonly number = inject(TestService).number;
}
// avec beforeEach
describe('TestComponent', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
describe('real service', () => {
beforeEach(async () => {
await TestBed.compileComponents();
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should display 123', () => {
expect(component.number).toEqual(123);
});
})
describe('fake service', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({ providers: [{provide: TestService, useValue: { number: 456 } }]}).compileComponents();
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should display 456', () => {
expect(component.number).toEqual(456);
})
})
})
// avec setup()
async function setup(mocks?: { testService?: TestService }) {
await TestBed.configureTestingModule({
providers: [mocks?.testService ? { provide: TestService, useValue: mocks.testService } : TestService }]
}).compileComponents();
const fixture = TestBed.createComponent(TestComponent);
return { fixture, component: fixture.componentInstance };
}
describe('TestComponent', () => {
it('should display 123', async () => {
const { component } = await setup();
expect(component.number).toEqual(123);
})
it('should display 456', async () => {
const { component } = await setup({testService: {number: 456 }});
expect(component.number).toEqual(456);
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment