Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a VUE component that have provide/inject?

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?

like image 269
Tran Son Hoang Avatar asked Dec 03 '18 04:12

Tran Son Hoang


People also ask

How do you test Vuejs applications?

We recommend using @testing-library/vue for testing components in applications, as its focus aligns better with the testing priorities of applications. Use @vue/test-utils only if you are building advanced components that require testing Vue-specific internals.


1 Answers

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.

like image 188
Slicksim Avatar answered Oct 08 '22 23:10

Slicksim