jeudi 11 mars 2021

How to inject Angular service for login in Cypress tests

I start using Cypress to test my Angular app. As recommended by Cypress, I would like to save testing time by bypassing the login screen upon each test, and directly invoke my Angular LoginService.

I followed this example: https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/logging-in__using-app-code as a basis (but it is not using Angular services).

The thing is that:

  • I have a LoginService with a login method taking a username and password as input. It contacts the server, and when the login works, it does some specific initializations in the application, which I need to be performed before running each test.
  • LoginService depends on another custom service, say MyOwnService, and on the HttpClient service
  • MyOwnService in turn depends on HttpClient, MatSnackBar and Router (which are regular Angular/Material services)

When the application is running normally (out of Cypress), all these services are automagically loaded thanks to dependency injection.

However from the Cypress test I tried the following:

import { LoginService } from '../../src/app/services/login.service'
import { MyOwnService } from 'src/app/services/my-own.service'
import { HttpClient } from '@angular/common/http'
...
it('should work', () => {
    let http = new HttpClient()
    let snackBar = new MatSnackBar()
    let router = new Router()
    let myo = new MyOwnService(http, snackBar, router)
    let ls = new LoginService(myo, http)
    cy.wrap(ls.login({username: 'foo', password: 'bar'}), {}).then(user => {
         cy.log("would be nice to reach this")
    })
})

But it is ugly, it does not work, for various reasons, including that the relative paths used to import extra packages in the MyOwnService code are no longer found, when loaded from Cypress.

Would you have some recommendation to make the dependency injection work from within Cypress? Or any working code sample?

Many thanks!

Aucun commentaire:

Enregistrer un commentaire