dimanche 18 octobre 2020

How to test simple Angular service with dependencies

I would like to understand how to test the service with dependencies created in Angular. This service has just one method which opening a Angular Material Snackbar and doesn't return anything. Depends on conditions there are two options to display - success or error. The service doesn't have public properties, everything is done in the only method it contains. The service has also some dependencies. Pseudocode below:

export class SnackbarService {

  constructor(private snackBar: MatSnackBar, private status: Status) { }

  openSnackBar(arg: string | Error):void {
    let prop1: string;
    let prop2: number;
    let prop3: string;

    if (arg instanceof Error) {
      prop1 = this.status.default;
      prop2 = 5000;
      prop3 = 'error';
    } else {
      prop1 = 'another status';
      prop2 = 6000;
      prop3 = 'success';
    }

    this.snackBar.open(prop1, 'x', {
      prop2,
      horizontalPosition: 'center',
      verticalPosition: 'top',
      prop3
    });

}

Now the tests. I was thinking it would be probably easier to test if above service would be written in another way - with public properties passed as arguments into two methods instead of one - the one which resolve the if statement and another one which actually opens the Snackbar. However let's say the code looks like above. What can be actually tested when method doesn't return anything and there are no public properties?

describe('SnackbarService', () => {
  let service: SnackbarService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        MatSnackBarModule
      ],
      providers: [
        SnackbarService
      ]
    });
    service = TestBed.inject(SnackbarService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

I know that dependencies should be imported to the tests but have no idea how to test anything else than the creation of the service itself. Appreciate any constructive hints!

Aucun commentaire:

Enregistrer un commentaire