如何使用 Jest 测试组件是否正确计算数组长度

Mah*_*eva 5 javascript unit-testing jestjs

我有一个组件,我给它一个带有对象作为道具的数组,如下所示:

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
  });
});
Run Code Online (Sandbox Code Playgroud)

如何测试提供的数组是否具有正确的长度,例如如果数组中有两个对象,组件应该返回两个,如果有一个,一个,如果没有则返回 0,我该怎么做达到那个?我试过

expect(component.length).toHaveLength(buttons).length
Run Code Online (Sandbox Code Playgroud)

但这不起作用

ken*_*ill 19

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

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

expect(comp.findAll(Button)).toHaveLength(buttons.length)
Run Code Online (Sandbox Code Playgroud)


Bor*_*ipt 9

我猜您想检查是否呈现了某种类型的正确数量的孩子(在 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)
Run Code Online (Sandbox Code Playgroud)

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