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

时间:2019-08-13 20:30:17

标签: 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
  });
});

如何测试提供的数组的长度正确,例如,如果数组中有两个对象,则组件应返回两个,如果有一个,则返回一个,如果没有,则应返回0,我该如何实现?我尝试过

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

但这不起作用

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

我猜您想检查是否正确渲染了某种类型的子代(在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