Home > other >  Angular: window.print() unit test
Angular: window.print() unit test

Time:04-09

I need help to write a unit test of my method but I don't know how to do it. So if anyone can give me a hand, you will save my day.

my method:

print(component) {
  window.print();
  window.cancel();
}

how can I test this method?

CodePudding user response:

Try something like this:

it('should call print and cancel', () => {
  // spy on print and cancel on window object
  const printSpy = spyOn(window, 'print');
  const cancelSpy = spyOn(window, 'cancel');

  // call print
  component.print({/* mock component however you wish here */});

  // expect print and cancel spy to have been called
  expect(printSpy).toHaveBeenCalled();
  expect(cancelSpy).toHaveBeenCalled();
});

If you're new to unit testing, this is a great resource: https://testing-angular.com/.

  • Related