12

I am writing some unit test but I got trouble with component that have inject property.

I am using shallowMount. I did some research about this.And there is way to create fake data for provide https://vue-test-utils.vuejs.org/api/options.html#provide. But, I didn't see any information or hints about inject.

So, I need some advices about How to do unit test with inject in Vuejs?

Hoang Subin
  • 6,610
  • 6
  • 37
  • 56

1 Answers1

12

What you set in the provide property is what is used to inject into the mounted component.

In my unit test I have

metadataModule = sandbox.createStubInstance(MetadataModule);
metadataService = sandbox.createStubInstance(MetadataService);

wrapper = shallowMount(MoveFileElement, {
        provide: {
            [SYMBOLS.METADATAMODULE]: metadataModule,
            [SYMBOLS.METADATASERVICE]: metadataService,
        },
        ....

Then in my component I have

export default class MoveFileElement extends Mixins(Utilities) {       
    @Inject(SYMBOLS.METADATAMODULE) public metadataModule!: IMetadataModule;
    @Inject(SYMBOLS.METADATASERVICE) public metadataService!: MetadataService;

Now the component has access to the fake versions of the metadata module that I prepared in the unit test.

Slicksim
  • 7,054
  • 28
  • 32
  • You mean that We will shallowMount `provide` at the component. So that When that component will see data at `inject` ??? – Hoang Subin Dec 06 '18 at 06:55
  • 1
    Yes, the elements you give to provide will be injected into the component. Two sides of the same coin – Slicksim Dec 06 '18 at 07:30
  • @Slicksim how do you test a change in your `provide`d data? in case you want to check how your component reacts to those changes – Tzahi Leh Jun 16 '21 at 17:07
  • @TzahiLeh you mean as in a watcher? – Slicksim Jun 21 '21 at 08:13
  • @Slicksim Exactly. I am watching an injected value, and I want to test the watcher. For that I need to change the provided data during the test - but how? – Tzahi Leh Jun 21 '21 at 11:38
  • @TzahiLeh, I don't think you should test that. Testing that when data is changed, that a watcher fires, that is not your code, the vuejs team would test that code. What you should test is that when your watcher function is called, that it sets the data or performs the actions that you want accordingly. Leave the testing of the watcher and your code together for integration tests, not unit tests – Slicksim Jun 22 '21 at 07:33
  • @Slicksim thanks, I understand. I didn't mean to test the **watcher** itself. The watcher invokes some functionality, for instance changes some data, or emits an event. In my case it does some *visual changes*, and I want to test these changes take place – Tzahi Leh Jun 22 '21 at 08:03