Testing Library (VueJS) - Rendering multiple components in a it block

1k views Asked by At

Relatively new to testing so this is probably super simple:

I want to test a checkbox component. I got the basics down, however, how can I render multiple components inside an it block?

My code so far. I am stuck on the second test, where I want to render multiple items and check one. That would should return its value (or however we can test the selected checkbox).

The component itself it quite simple. It has a label and checkbox element and receives all the props you would expect.

Thank you!

import { render } from '@testing-library/vue';
import OBCheckbox from '../OBCheckbox.vue';

describe('OBCheckbox', () => {
    it('should be selected', async () => {
        const label = 'checkboxLabel1';
        const value = 'Testing Value';
        const { getByLabelText } = render(OBCheckbox, { props: { label, value } });

        const checkBox = getByLabelText(label);
        expect(checkBox).toBeChecked(value);
    });
    it('should return selected items value', async () => {
        // stuck here
    });
    it('should be disabled', async () => {
        const label = 'checkboxLabel1';
        const value = 'Testing Value';
        const disabled = true;
        const { getByLabelText } = render(OBCheckbox, { props: { label, value, disabled } });

        const checkBox = getByLabelText(label);
        expect(checkBox).toBeDisabled();
    });
    it('should be accessible', async () => {
        const label = 'checkboxLabel1';
        const value = 'Testing Value';
        const { getByRole } = render(OBCheckbox, { props: { label, value } });

        const checkBox = getByRole('checkbox');
        expect(checkBox).toBeChecked(value);
    });
});
1

There are 1 answers

0
Sangil Yun On

I'm not sure what multiple components you are trying to render in one it block but if what you are trying to do is rendering multiple OBCheckbox in one it block, then probably you can do something like this.

import { screen, render } from '@testing-library/vue';

it('should return selected items value', () => {
    render({
        template:`
            <div>
                <your_component :label="'label1'" :value="'value1'"/>                
                <your_component :label="'label2'" :value="'value2'"/>
                <your_component :label="'label3'" :value="'value3'"/>
            </div>
        `,
        components:{ your_component }
    })

    // assuming the label of the component is associated with its input by input's id
    const selectedCheckbox = screen.getByRole('checkbox', { name: 'label1' })
    expect(selectedCheckbox).toBe(...)
})