nolannordlund's avatar

V-for isn't rendering items in my test

I have a simple component that should show a list of items as well as a new item button

<template>
    <div>
        <ul ref="item-list">
            <li v-for="item in items" :key="item.id" id="item.id">{{ item.title }}</li>
            <li ref="new-item" @click="$emit('newItem')">New item</li>
        </ul>
    </div>
</template>

<script>
export default {
    data: function() {
        return {
            items: []
        };
    }
};
</script>

I am trying to test that the correct number of li elements are displayed

describe('LibrarySelector', () => {
    let wrapper;

    beforeEach(() => {
        wrapper = mount(LibrarySelector);

        wrapper.setData({ items: [
            {id: 1, title: 'Some Title'},
            {id: 2, title: 'Another item'},
        ]});
    }); 


    it ('displays all items', () => {
        expect(wrapper.findAll('li').length).toBe(3)
    });
});

The test is failing, showing only 1 item. None of the items that I am trying to send in the setData function are being displayed.

0 likes
4 replies
bugsysha's avatar

And what about

expect(wrapper.vm.items.length).toBe(2)
bugsysha's avatar
bugsysha
Best Answer
Level 61

Also I know there shouldn't be any issues but have you tried

const wrapper = mount(LibrarySelector, {
    data() {
      return {
        items: [
            {id: 1, title: 'Some Title'},
            {id: 2, title: 'Another item'},
        ]
      }
    }
  })

expect(wrapper.vm.items.length).toBe(2)
expect(wrapper.findAll('li').length).toBe(3)
nolannordlund's avatar

Both of those work, thanks. Why is it that I can pass the data in the mount method but setData doesn't seem to do anything?

bugsysha's avatar

Not sure what is the issue there. I think I had it long time ago, but never bothered to inspect it. But back then VueTestTools was a new thing so I though it might have some hiccups which will get sorted. I know that I've used setData() successfully. If you figure it out please post back and mention me.

Please or to participate in this conversation.