Hoang Subin
Hoang Subin

Reputation: 7460

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?

Upvotes: 14

Views: 13079

Answers (1)

Slicksim
Slicksim

Reputation: 7172

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.

Upvotes: 12

Related Questions