使用 Jest 在 Vue 中为组件中的方法编写单元测试

     2023-02-22     241

关键词:

【中文标题】使用 Jest 在 Vue 中为组件中的方法编写单元测试【英文标题】:Write unit test for a method in a component in Vue with Jest 【发布时间】:2021-09-05 17:57:36 【问题描述】:

我开始使用 Jest Vue 进行单元测试。我想测试一个 Vue 组件中的现有方法,我写了一个测试但它没有通过。而且我不知道如何在测试中模拟和调用该方法。

如何编写一个好的单元测试,以传递 'goPage()' 方法的功能?

我的方法是:

goPage(id, name, categoryId) 
   this.headerSearchInput = name
   this.$router.push(
      path: '/categories/' + categoryId + '/courses/' + id,
      query:  query: this.headerSearchInput ,
   )

我的测试是:

import  shallowMount, createLocalVue  from '@vue/test-utils'
import HeaderSearch from '../../components/header/HeaderSearch.vue'

const localVue = createLocalVue()
localVue.use(VueRouter)
const router = new VueRouter()

describe('Header search component', () => 
   const mockRoute = 
      path: '/categories/' + 2 + '/courses/' + 4,
      query: 
        query: searchedText,
      ,
   
   const mockRouter = 
      push: jest.fn(),
   
   const wrapper = shallowMount(HeaderSearch, 
      router,
      localVue,
      stubs: 
        NuxtLink: true,
      ,
      global: 
        mocks: 
          $route: mockRoute,
          $router: mockRouter,
        ,
      ,
   )
   test('redirect to course page, goPage', async () => 
      const courseId = 4
      const courseTitle = 'Inbound Marketing'
      const categoryId = 2

      const mockedFunction = jest.fn()
      wrapper.vm.goPage(courseId, courseTitle, categoryId)
      await wrapper.setData(
        headerSearchInput: courseTitle,
      )
      const expectedRouter = 
        path: '/categories/3/courses/4',
        query:  query: wrapper.vm.headerSearchInput ,
      
      expect(mockedFunction).toBeCalledWith(courseId, courseTitle, categoryId)
      expect(wrapper.vm.$router.path).toEqual(expectedRouter.path)
   )
)

【问题讨论】:

【参考方案1】:

当您测试路由时,您应该只使用模拟而不在您的 local Vue 实例上安装 VueRouter。正如官方documentation 所说:

在 localVue 上安装 Vue 路由器还会将 $route 和 $router 作为只读属性添加到 localVue。这意味着在使用安装了 Vue Router 的 localVue 安装组件时,您不能使用 mocks 选项覆盖 $route 和 $router。

所以你需要在shallowMount 调用中获取localVue 的reed,只留下$router 嘲笑:

然后在测试中,您只需调用您的 goPage 方法并检查 $router.push() 是否使用特定参数调用。 不检查 $route.path 是否已更改,将其留给端到端测试。

let wrapper
describe('HelloWorld.vue', () => 
  beforeEach(() => 
    wrapper = shallowMount(HelloWorld, 
      global:  mocks:  $router:  push: jest.fn()   
    )
  )

  test('redirect to course page, goPage', async () => 
    const courseId = 4
    const courseTitle = 'Inbound Marketing'
    const categoryId = 2
    const expectedRouter = 
      path: '/categories/' + categoryId + '/courses/' + courseId,
      query:  query: 'Inbound Marketing' 
    
    wrapper.vm.goPage(courseId, courseTitle, categoryId)
    expect(wrapper.vm.$router.push).toBeCalledWith(expectedRouter)
  )
)

【讨论】:

我像你说的那样写了测试,但是它抛出了Cannot read property 'push' of undefined 错误。我该如何解决? @爱德华多 请提供带有包装器实例化的测试代码。 代码很长,所以我用2个cmets来写。 const wrapper = shallowMount(HeaderSearch, stubs: NuxtLink: true, , global: mocks: $router: push: jest.fn(), , , , ) test('redirect to course page, goPage', async () => const courseId = 4 const courseTitle = 'Inbound Marketing' const categoryId = 2 const expectedRouter = path: '/categories/' + categoryId + '/courses/' + courseId, query: query: wrapper.vm.headerSearchInput , wrapper.vm.goPage(courseId, courseTitle, categoryId) await wrapper.setData( headerSearchInput: courseTitle, ) expect(wrapper.vm.$router.push).toBeCalledWith(expectedRouter) ) 我已经更新了我的答案,请检查一下。【参考方案2】:

我解决了我的问题,如下所示:

let wrapper
describe('HeaderSearch', () => 
   const $route = 
     path: '/categories/2/courses/4',
   
   const $router = 
     push: jest.fn(),
   
   beforeEach(() => 
   wrapper = shallowMount(HeaderSearch, 
      mocks: 
        $route,
        $router,
      ,
  )
)

test('go to each course page', () => 
  const courseId = 4
  const categoryId = 2
  const courseTitle = 'Inbound Marketing'

  wrapper.vm.goPage(courseId, courseTitle, categoryId)
  const expectedRouter = 
    path: '/categories/' + categoryId + '/courses/' + courseId,
    query:  query: courseTitle ,
  
  expect(wrapper.vm.$router.push).toBeCalledWith(expectedRouter)
  )
)

【讨论】:

在 Nuxt、Vue、jest 和 Vuetify 中为项目编写单元测试

...的组件的实际单元测试没有通过。详情:我正在开发一个使用Vue、NUXT、Vuetify和pug作为模板语言构建的 查看详情

Vue Test Utils / Jest - 如何测试是不是在组件方法中调用了类方法

】VueTestUtils/Jest-如何测试是不是在组件方法中调用了类方法【英文标题】:VueTestUtils/Jest-HowtotestifclassmethodwascalledwithinacomponentmethodVueTestUtils/Jest-如何测试是否在组件方法中调用了类方法【发布时间】:2019-01-2500:42:50【问题描述】... 查看详情

使用 Jest / Enzyme 在 React 中的功能组件内部测试方法

】使用Jest/Enzyme在React中的功能组件内部测试方法【英文标题】:TestingmethodinsidefunctionalcomponentinReactusingJest/Enzyme【发布时间】:2020-07-1721:30:17【问题描述】:以下是我尝试使用jest/enzyme测试的React功能组件。React功能组件代码-export... 查看详情

如何测试是不是使用 Jest 调用了 Vue 方法?

】如何测试是不是使用Jest调用了Vue方法?【英文标题】:HowdoItestifaVuemethodwascalledusingJest?如何测试是否使用Jest调用了Vue方法?【发布时间】:2021-09-0614:58:04【问题描述】:我正在尝试进行测试,看看是否在按下按钮时调用了我... 查看详情

Vue Typescript 组件 Jest 测试不会在 html 中呈现值

...【发布时间】:2021-02-0217:48:15【问题描述】:我正在尝试使用Typescript专注于TDD,因此我使用vue-cli构建了一个新的Vue项目(我选择使用Vue3、Typescript和Jest)。但是,当我开箱即用地运行单 查看详情

Vue & Jest。子组件发出事件时调用测试方法

...21-02-0416:27:07【问题描述】:因此,在Vue-test-utils中不推荐使用setMethods之后,我将更改我的测试以使用jest.spyOn。我只是想从子组件发出一个事件并检查父组件上是否调用了相应的方法,但不 查看详情

使用 Jest 运行测试时,为啥 Trix 编辑器不会安装在 Vue 组件中?

】使用Jest运行测试时,为啥Trix编辑器不会安装在Vue组件中?【英文标题】:Whywon\'tTrixeditormountinVuecomponentwhenrunningtestswithJest?使用Jest运行测试时,为什么Trix编辑器不会安装在Vue组件中?【发布时间】:2019-09-1807:19:44【问题描述... 查看详情

用 jest 测试 Vue 过滤器

...【发布时间】:2018-07-0202:26:09【问题描述】:我正在尝试使用jest为我的Vue项目中的一个过滤器编写测试,我可以在不使用任何组件的情况下测试该过滤器吗?我的意思是我可以将它作为一个单元(如函数)进行测试吗?我搜索... 查看详情

如何使用 jest 测试 Vue.js 组件中方法的错误

】如何使用jest测试Vue.js组件中方法的错误【英文标题】:HowtotestanErrorofaMethodinaVue.jsComponentusingjest【发布时间】:2020-04-0108:58:48【问题描述】:如何测试我的Vue组件的方法createUser()?我想测试createUser()方法是否会抛出Error如果first... 查看详情

Vue 组合 API + Jest

...用Vue3组合API,但在为它编写测试时遇到了一些问题。我使用组合API在我的应用程序中编写了新组件(MyComponent)。MyComponent使用另一个使用Optionsapi(MyOtherComponent)编写的组件。如果我运行该应用程序一切正常,但是当我编写单元测... 查看详情

Jest/Enzyme 使用 try/catch 中的 async/await 方法测试 React 组件

】Jest/Enzyme使用try/catch中的async/await方法测试React组件【英文标题】:Jest/EnzymetestReactcomponentwithasync/awaitmethodintry/catch【发布时间】:2019-08-1216:32:17【问题描述】:多年来,我一直在努力尝试用Jest测试这种方法,在线搜索似乎没有... 查看详情

如何在单文件组件中正确使用 Vue Router beforeRouteEnter 或 Watch 触发方法?

】如何在单文件组件中正确使用VueRouterbeforeRouteEnter或Watch触发方法?【英文标题】:HowtoProperlyUseVueRouterbeforeRouteEnterorWatchtotriggermethodinSingleFileComponent?【发布时间】:2017-10-1721:55:38【问题描述】:我正在使用单文件组件和Vue路由... 查看详情

使用 Jest 和 vue-utils 测试 Vue 组件

】使用Jest和vue-utils测试Vue组件【英文标题】:TestVuecomponentsusingJestandvue-utils【发布时间】:2019-04-1920:52:09【问题描述】:我正在尝试使用jest和vue-utils测试在vue中调用的组件,但它给出了以下错误expect(jest.fn()).toHaveBeenCalled()Expected... 查看详情

Vue 和 Jest 单元测试组件

...:2019-01-0209:17:46【问题描述】:我是Vuejs的新手,我开始使用Jest进行单元测试。我不知道从哪里以及如何开始。我有这段Vue代码,我想用Jest进行测试。任何提示或想法我都会非常感激。我读到我应该使用Vuetest-utils中的shallowMount... 查看详情

如何使用 jest 在单元测试中测试引导 vue 组件的存在?

】如何使用jest在单元测试中测试引导vue组件的存在?【英文标题】:Howtotestfortheexistanceofabootstrapvuecomponentinunittestswithjest?【发布时间】:2019-11-2117:30:00【问题描述】:所以我有一些包含b-form-input组件的代码,我正在测试该组件是... 查看详情

使用 Vue.js 和 Jest 进行 URL 重定向测试

】使用Vue.js和Jest进行URL重定向测试【英文标题】:URLredirectiontestingwithVue.jsandJest【发布时间】:2018-07-3100:55:27【问题描述】:我正在尝试编写一个测试来检查当用户单击“登录”按钮时,URL是否被重定向到/auth/。前端是用Vue.js编... 查看详情

在使用 jest 的 vue 测试中找不到模块“@jest/globals”

】在使用jest的vue测试中找不到模块“@jest/globals”【英文标题】:Cannotfindmodule\'@jest/globals\'inavuetestusingjest【发布时间】:2020-08-3020:15:15【问题描述】:我正在尝试从我的项目中的vue文档编写一个非常简单的测试。我可以在我的项... 查看详情

如何在挂载事件中为vue组件数据成员赋值[重复]

】如何在挂载事件中为vue组件数据成员赋值[重复]【英文标题】:Howtoassignavaluetoavuecomponentdatamemberinmountedevent[duplicate]【发布时间】:2018-12-1015:36:53【问题描述】:我一直在阅读vue文档并开始编写一些代码来测试我的知识。我试图... 查看详情