无法通过用jest进行的vue js单元测试

nszi6y05  于 2023-02-27  发布在  Jest
关注(0)|答案(1)|浏览(207)

我有一个vue.JS组件,在其中安装时,执行函数getIngredients:

mounted() {
   if (this.cocktail) {
     this.getIngredients();
   }
}

我有一个单元测试无法通过:

it('Call getIngredients function when the component is mounted', async () => {
    const getIngredientsMock = jest.fn()
    const wrapper = shallowMount(CocktailCard, {
      propsData: {
        cocktail: {
          idDrink: '1',
          strDrink: 'Mojito',
        }
      },
      methods: {
        getIngredients: getIngredientsMock
      }
    })
    expect(getIngredientsMock).toHaveBeenCalled()
  });

我想检查在安装组件时是否执行了getIngredients函数
错误:

› Call getIngredients function when the component is mounted
                                                                                                                                                                                       
    expect(jest.fn()).toHaveBeenCalled()                                                                                                                                               
                                                                                                                                                                                       
    Expected number of calls: >= 1                                                                                                                                                     
    Received number of calls:    0                                                                                                                                                     

      22 |       }
      23 |     })
    > 24 |     expect(getIngredientsMock).toHaveBeenCalled()
         |                                ^
      25 |   });
      26 | })

      at Object.<anonymous> (tests/unit/CocktailCard.spec.js:24:32)
pqwbnv8z

pqwbnv8z1#

请尝试改为探查方法。

it('Call getIngredients function when the component is mounted', async () => {
  const getIngredientsMock = jest.spyOn(CocktailCard.methods, 'getIngredients')
  const wrapper = shallowMount(CocktailCard, {
    propsData: {
      cocktail: {
        idDrink: '1',
        strDrink: 'Mojito',
      }
    },
  })
  expect(getIngredientsMock).toHaveBeenCalled()
})

相关问题