Home > Back-end >  How to mount Angular components in Cypress?
How to mount Angular components in Cypress?

Time:11-02

I am trying to test individual components for my Angular project following the guidelines set up in the official Cypress 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.

CodePudding user response:

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

CodePudding user response:

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]
    })
  })
})

CodePudding user response:

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.

  • Related