Vue Testing Library: How to mock Vue component

1.9k views Asked by At

I used React Testing-Library, but not Vue Testing-Library before https://testing-library.com/docs/vue-testing-library/intro/ and I don't want to use mount or shallowMount where I can provide a stub. I want to figure out how to do that in VTL.

We usualy have components that use other components. So when testing our component say ComponentA it may use ComponentB and ComponentC. While there are some components that we want to be rendered (ComponentA and ComponentB) and want to test how they interact with our component, there are also others (ComponentC), which we may not want to test here, because they have their own tests. I.e. we want to "shallow-render" ComponentC when testing ComponentA.

Using react testing library we can do this:

import * as mockedComponentCModule from '....ComponentC';

jest.spyOn(mockedComponentCModule, 'ComponentC').mockImplementation(() => (
    <div data-testid="mocked-component-c" />
));

or I like this

jest.mock('path/to/my/ComponentC', () => ({
    ComponentC: function ComponentC() {
        return <div data-testid="mocked-component-c" />;
    }
}));

So in react when we do render(<ComponentA />) the ComponentC will render as a simple div instead of the actual component.

My question is - how can I do this with Vue Testing Library?

2

There are 2 answers

2
Csonter On BEST ANSWER

I think what you are looking for is stubs.

With vue testing library you can do this:

const wrapper = render(Component, { stubs: { ComponentToStub: true } }

Or instead of true you could also provide a string I think.

1
nsimeonov On

I think I figured it out:


jest.spyOn(mockedComponentCModule.default, 'render').mockImplementation((create) =>
    create('div', { attrs: { 'data-testid': 'mocked-component-c' } }, 'Test Content')
);

Now sure if there's a better way - I'd be thankful if someone points me in the right direction