0

I have the following code

this.myEvent.emit(new MyModel({prop1: true, prop2: 'someString', someOtherProps...}))

In jasmine I have

const spy = spyOn(component.myEvent, 'emit');

How can I check that myEvent has emitted an object with property prop1 = true?

AngularDebutant
  • 1,436
  • 5
  • 19
  • 41
  • Don't spy on the thing you're supposed to be testing, see e.g. https://angular.io/guide/testing-components-scenarios#component-inside-a-test-host – jonrsharpe Jul 10 '20 at 07:46
  • Hmm, how would I then check that the `component.myEvent.emit` has been called? `toHaveBeenCalledTimes` expects a spy not a function. – AngularDebutant Jul 10 '20 at 07:52
  • You wouldn't, because that's an implementation detail. Test the actual behaviour, which is that a parent component binding myEvent would receive the right value at the right time. – jonrsharpe Jul 10 '20 at 07:54
  • @jonrsharpe Okay, well then imagine I am in the parent component, and I want to test that the child has emitted an object with property `prop1 = true`? So the question stands. – AngularDebutant Jul 10 '20 at 08:04
  • @jonrsharpe please see https://stackoverflow.com/a/35319780/8188883 – AngularDebutant Jul 10 '20 at 08:07
  • Sadly lots of people do the wrong thing, because it seems easy and they don't know any better. Here's the right answer, from someone who's got a lot of Angular knowledge, in line with the guidance in the official docs I already shared: https://stackoverflow.com/a/35319537/3001761. And if in the test host you want to check that the `prop1` property of the emitted value is `true`, what is stopping you from `expect(emittedValue.prop1).toBe(true)`? – jonrsharpe Jul 10 '20 at 08:14
  • @jonrsharpe the issue I have is that prop1 is a constructor argument, so in a way I have to check that `MyModel` has been instantiated with prop1 = true. – AngularDebutant Jul 10 '20 at 08:24
  • No, you don't. You have to test that the behaviour of the emitted value is consistent with that value having been true. If it's exposed as a prop that's obviously straightforward, if not then we can't tell you how to test that without seeing the implementation of MyModel. Otherwise you're testing that a test double of the emitter was called with a test double of the model that was called with an object, which is too coupled to current implementation. – jonrsharpe Jul 10 '20 at 08:27

0 Answers0