Testing Angular 14 Standalone Components with Spectator

2.2k Views Asked by At

Our test runner is Jest.

Our component is marked as standalone: true,

If try to set up spectator like this:

describe('OurComponent', () => {
    let spectator: Spectator<OurComponent>;

    const fakeActivatedRoute: ActivatedRoute = {
        snapshot: {data: {}},
    } as ActivatedRoute;

    const componentFactory: SpectatorFactory<OurComponent> = createComponentFactory({
        component: OurComponent,
        imports: [
            // some imports
        ],
        providers: [
           // some providers
        ],
        detectChanges: false,
        shallow: true,
    });

    beforeEach(async () => {
        spectator = componentFactory();
    });

    it('should be created', () => {
        expect(spectator).toBeDefined();
    });
});

Then we run into the following error: "Error: Unexpected "OurComponent" found in the "declarations" array of the "TestBed.configureTestingModule" call, "OurComponent" is marked as standalone and can't be declared in any NgModule - did you intend to import it instead (by adding it to the "imports" array)?"

Using the Angular-CLI in order to generate resulted in a component with a test file which is built upon ComponentFixture.

How can we make it possible to test a standalone component using Spectator?

1

There are 1 best solutions below

1
On BEST ANSWER

Depends on your spectator version (mine is 10.0.0) but you can use the declareComponent property :

const componentFactory: SpectatorFactory<OurComponent> = createComponentFactory({
    component: OurComponent,
    declareComponent: false,
});