angular/packages/core/testing/src/testing.ts
Kristiyan Kostadinov 2e0c98bd3f feat(core): support bindings in TestBed (#62040)
Adds support for passing in `Binding` objects into `TestBed.createComponent`. This makes it easier to test components by avoiding the need to create a wrapper component. Furthermore, it keeps the behavior consistent between tests and the actual app. For example, given a custom checkbox that looks like this:

```typescript
@Component({
  selector: 'my-checkbox',
  template: '...',
  host: {'[class.checked]': 'isChecked()'}
})
export class MyCheckbox {
  isChecked = input(false);
}
```

A test for the `isChecked` input would look something like this:

```typescript
it('should toggle the checked class', () => {
  @Component({
    imports: [MyCheckbox],
    template: '<my-checkbox [isChecked]="isChecked"/>',
  })
  class Wrapper {
    isChecked = false;
  }

  const fixture = TestBed.createComponent(Wrapper);
  const checkbox = fixture.nativeElement.querySelector('my-checkbox');
  fixture.detectChanges();
  expect(checkbox.classList).not.toContain('checked');

  fixture.componentInstance.isChecked = true;
  fixture.detectChanges();
  expect(checkbox.classList).toContain('checked');
});
```

Whereas with the new API, the test would look like this:

```typescript
it('should toggle the checked class', () => {
  const isChecked = signal(false);
  const fixture = TestBed.createComponent(MyCheckbox, {
    bindings: [inputBinding('isChecked', isChecked)]
  });
  const checkbox = fixture.nativeElement.querySelector('my-checkbox');
  fixture.detectChanges();
  expect(checkbox.classList).not.toContain('checked');

  isChecked.set(true);
  fixture.detectChanges();
  expect(checkbox.classList).toContain('checked');
});
```

PR Close #62040
2025-06-17 11:49:27 +02:00

48 lines
1.1 KiB
TypeScript

/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the core/testing package.
*/
export * from './async';
export {ComponentFixture} from './component_fixture';
export {
resetFakeAsyncZone,
discardPeriodicTasks,
fakeAsync,
flush,
flushMicrotasks,
tick,
} from './fake_async';
export {
TestBed,
getTestBed,
TestBedStatic,
inject,
InjectSetupWrapper,
withModule,
TestComponentOptions,
} from './test_bed';
export {
TestComponentRenderer,
ComponentFixtureAutoDetect,
ComponentFixtureNoNgZone,
TestModuleMetadata,
TestEnvironmentOptions,
ModuleTeardownOptions,
} from './test_bed_common';
export * from './metadata_override';
export {MetadataOverrider as ɵMetadataOverrider} from './metadata_overrider';
export {
ɵDeferBlockBehavior as DeferBlockBehavior,
ɵDeferBlockState as DeferBlockState,
} from '../../src/core';
export {DeferBlockFixture} from './defer';