测试在安装组件时调用方法

Testing that a method is called when component is mounted

我正在尝试测试在安装组件时是否调用了一个方法,但它一直失败

Expected mock function to have been called one time, but it was called zero times.

这是组件:

<template>
  <b-form-input
    class="mr-2 rounded-0"
    placeholder="Enter Search term..."
    id="input-keyword"
  />
</template>
<script>
export default {
  name: 'job-search-test',
  methods: {
    async searchJobs () {
      console.log('Calling Search Jobs from JobsSearchTest')
    }
  },
  mounted () {
    this.searchJobs()
  }
}
</script>

这是测试:

import { shallowMount, createLocalVue } from '@vue/test-utils'
import BootstrapVue from 'bootstrap-vue'
import JobSearchTest from '@/components/jobs/JobSearchTest'

const localVue = createLocalVue()
localVue.use(BootstrapVue)

describe('JobsSearchTest.vue', () => {
  it('should call searchJobs method when component is mounted', () => {
    const methods = {
      searchJobs: jest.fn()
    }
    shallowMount(JobSearchTest, {
      mocks: {
        methods
      },
      localVue })
    expect(methods.searchJobs).toHaveBeenCalledTimes(1)
  })
})

但是,下面的测试通过了

import { shallowMount, createLocalVue } from '@vue/test-utils'
import BootstrapVue from 'bootstrap-vue'
import JobSearchTest from '@/components/jobs/JobSearchTest'

const localVue = createLocalVue()
localVue.use(BootstrapVue)

describe('JobsSearchTest.vue', () => {
  it('should call searchJobs method when component is mounted', () => {
    let searchJobs = jest.fn()
    shallowMount(JobSearchTest, {
      methods: {
        searchJobs
      },
      localVue })
    expect(searchJobs).toHaveBeenCalledTimes(1)
  })
})

根据 Edd Yerburgh 的《测试 VueJs 应用程序》,通过以下方式用 Jest 模拟对函数进行存根来测试函数

  it('should call $bar.start on load', () => {
    const $bar = {
      start: jest.fn(),
      finish: () => {}
    }
    shallowMount(ItemList, { mocks: $bar })
    expect($bar.start).toHaveBeenCalledTimes(1)
  })

在我看来,这基本上就是我在第一次测试中所做的,但失败了。

任何关于为什么会发生这种情况的帮助将不胜感激。

mocks option 模拟实例属性。 mocks: { methods } 假设 Vue 组件中有 methods 属性。由于未调用 this.methods.searchJobs(),因此测试失败。

这是 searchJobs 方法,测试应该如工作片段所示:

shallowMount(JobSearchTest, {
  methods: {
    searchJobs
  },
  localVue })