/cypress-angular-unit-test

Trying to load and bootstrap Angular component dynamically inside Cypress

Primary LanguageTypeScript

cypress-angular-unit-test BETA renovate-app badge cypress version ci status

Installation

npm install -D cypress cypress-angular-unit-test

Add to your support file

// cypress/support/index.js
// core-js 3.*
require('core-js/es/reflect')
// core-js 2.*
require('core-js/es7/reflect')
require('cypress-angular-unit-test/support')

Enable experimental component testing mode in cypress.json and point at the spec files. Usually they are alongside your application files in src folder.

{
  "experimentalComponentTesting": true,
  "componentFolder": "src",
  "testFiles": "**/*cy-spec.*"
}

Configure cypress/plugins/index.js to transpile Angular code.

TODO still under development

See blocker issue for Angular9 here

Use

import { mount } from 'cypress-angular-unit-test'
import { AppComponent } from './app.component'

describe('AppComponent', () => {
  it('shows the input', () => {
    // Init Angular stuff
    initEnv(AppComponent);
    // component + any inputs object
    mount(AppComponent, {title: 'World'})
    // use any Cypress command afterwards
    cy.contains('Welcome to World!')
  })
})

Demo

Under the hood, it's based on TestBed, you can use it by calling :

getCypressTestBed()

// Don't call TestBed.* directly in your spec !

// So, to inject a Service you can do :
const componentService = getCypressTestBed().inject(SomeService);

Examples

Use case Description
Input Test inject @Input() value
Output Test catching @Output()
Bootstrap Bootstrap integration with style : setConfig({ stylesheet: 'https://...});
Add style Add custom style for testing : setConfig({ style: 'p {background-color: blue;}' });
HTML mount Mount a component with html, don't forget to call detectChanges() after
Image Snapshot Mount a component and visual asserting
Material Material integration
OnPush strategy Component with changeDetection: ChangeDetectionStrategy.OnPush need call detectChanges()
Directive Test directive with mountHtml
Pipe Test pipe with mountHtml
Stub service Stub a service with Observable

Internal

External

Working

I have successfully used this mounting approach to test components in other frameworks.

Development

This project only transpiles the library, to see it in action:

  1. switch to the example project like cd examples/ng7
  2. install it with npm i
  3. open Cypress with npx cypress open

Pick any component test spec file to run