jeudi 25 février 2021

Best practices for mocking an emit when testing a child component in Jest (Vue)

I am testing a whole bunch of child components, and I'm running into something that I think is really bad practice. Whenever I hit an emit in a child component, it wants me to import the parent component, which then wants me to import and set up all of the other child components that parent calls. I want to be able to mock the emit in the child so that I can test that it is being called in general without testing the actual parent function that is being called, since that is tested in the parent component.

So for example:

myMethod() {
      //do something
      this.$emit('some-emit',someArgument);
      //do something else
    },

I want to be able to test myMethod and when it hits this.$emit for it to return some kind of mocked result, something like this:

it('should mock the emit', () => {
  const someEmitSpy = jest.spyOn($emit, someArg);
  myComponent.myMethod; // run this using someEmitSpy instead of this.$emit
  //expect blah blah
}

Aucun commentaire:

Enregistrer un commentaire