Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 631
Mahma Deva Avatar asked Aug 13 '19 20:08

Mahma Deva


People also ask

How do you check the length of an array?

The simplest procedural way to get the value of the length of an array is by using the sizeof operator. First you need to determine the size of the array. Then you need to divide it by the size of one element. It works because every item in the array has the same type, and as such the same size.

How do I find the length of an array in React?

js file and add the following code: import React from 'react' class App extends React. Component { render(){ const array = ["React","is", "awesome", "!"]; const length = array. length; return( <div> <p>Array length is { length }.

How do you test an array?

Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .

What is deep equality in Jest?

toEqual when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity—this is also known as "deep equal". For example, toEqual and toBe behave differently in this test suite, so all the tests pass.


Video Answer


2 Answers

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

like image 169
BorisTB Avatar answered Oct 30 '22 12:10

BorisTB


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

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

expect(comp.findAll(Button)).toHaveLength(buttons.length)
like image 21
kendotwill Avatar answered Oct 30 '22 12:10

kendotwill