Skip to content
Advertisement

How to test if component counts array length properly with Jest

I have a component that I am giving an array with objects as props to it like this:

describe('component', () => {
  it('should return the correct number of items passed in the array', () => {
    const comp = shallowMount(component, {propsData: {
      buttons: [
        {name:'button1'},
        {name:'button2'}
      ]
    }});
    expect(component.length).toHaveLength(buttons).length
  });
});

How can I test that the provided array has the correct length, for example if there are two objects in the array, the component should return two, if there is one, one, if there are none then it should return 0, how can I achieve that? I tried

expect(component.length).toHaveLength(buttons).length

But that does not work

Advertisement

Answer

I guess you want to check if the correct number of childs of some type was rendered (in Vue).

// import component that you want to count, e.g. Button

const buttons = [
  { name: 'button1' },
  { name: 'button2' }
]

const comp = shallowMount(component, { propsData: { buttons } })

expect(comp.findAll(Button).length).toBe(buttons.length)

https://lmiller1990.github.io/vue-testing-handbook/finding-elements-and-components.html#findall

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement