How to use Cypress Component Testing for Service-Tests in Angular?

690 views Asked by At

In my App, I want to implement Unit-Tests via "Cypress Component Tests". There is a lot of information about how to write Tests for Angular COMPONENTS using e.g. the cy.mount() command.

However, Im looking for information, on how to tests service-classes. I can't find any inforamtion about that topic.

Can you help me whith that?

Greetings!

1

There are 1 answers

0
T Klugg On

Testing the functionality (internals) of Angular services is given here app/demo/demo.spec.ts

All the example tests run in Cypress, except the last which uses jasmine.createSpyObj, but you could substitute the Cypress spy or stub commands.

describe('MasterService without Angular testing support', () => {
  let masterService: MasterService;

  it('#getValue should return real value from the real service', () => {
    masterService = new MasterService(new ValueService());
    expect(masterService.getValue()).toBe('real value');
  });

  it('#getValue should return faked value from a fakeService', () => {
    masterService = new MasterService(new FakeValueService());
    expect(masterService.getValue()).toBe('faked service value');
  });

  it('#getValue should return faked value from a fake object', () => {
    const fake =  { getValue: () => 'fake value' };
    masterService = new MasterService(fake as ValueService);
    expect(masterService.getValue()).toBe('fake value');
  });
})

You would (maybe) also want to test service integration with a component, which is shown here Imports/Declarations/Providers where DataService is the service to be tested.

cy.mount(ComponentThatFetchesData, {
  imports: [HttpClientModule],
  declarations: [ButtonComponent],
  providers: [DataService],
})

After mounting you can check the effect on the component, for example does the component display the data provided by the DataService.