liberlux
liberlux

Reputation: 109

How to mount Angular components in Cypress?

I am trying to test individual components for my Angular project following the guidelines set up in the official Cypress documentation.

I have created the following cy.ts file for one of my components

import {SpInputComponent} from "[abriged]/sp-input.component";

describe('Sp-Input component', () => {
  it('mounts', () => {
    cy.mount('<app-sp-input></app-sp-input>', {
      declarations: [SpInputComponent]
    })
  })
})

Unfortunately, when I try to run the test in Cypress, I get the following NullInjectionError. enter image description here

The component in question uses a service that is dependent on HttpClient (i.e. uses HttpClient in its constructor). I tried importing the HttpClient module as well as the service that uses it into the test file without success.

Any suggestions would be appreciated.

Upvotes: 0

Views: 2227

Answers (3)

liberlux
liberlux

Reputation: 109

Thank you for the answers but I discovered what the problem was. I had to add the providers 'attribute', as you rightfully pointed out, and added the services that were mentioned in the error message. In my case it was my custom ToolboxRepositoryService, the HttpClient and HttpHandler from angular's http module.

Upvotes: 1

user796446
user796446

Reputation:

A bit of a guess since you haven't posted your component under test but:

import {SpInputComponent} from "[abriged]/sp-input.component";
import { HttpClientTestingModule } from '@angular/common/http/testing';

describe('Sp-Input component', () => {
  it('mounts', () => {
    cy.mount('<app-sp-input></app-sp-input>', {
      declarations: [SpInputComponent],
      providers: [HttpClientTestingModule]
    })
  })
})

Upvotes: 0

Yew Hong Tat
Yew Hong Tat

Reputation: 694

You are missing the http client module import, MountConfig is an extension from Angular TestModuleMetadata. So you just need to add the import like the example below.

describe('Sp-Input component', () => {
  it('mounts', () => {
    cy.mount('<app-sp-input></app-sp-input>', {
      declarations: [SpInputComponent],
      imports: [HttpClientTestingModule] // <-- you need this
    })
  })
})

enter image description here

Upvotes: 0

Related Questions