2

我已将 Cypress Vue 组件测试运行器添加到现有的 Vue(vite) 应用程序中。但是,当我运行测试时,我收到一个错误,即我的组件中的 $route 未定义。我的组件测试设置是否遗漏了什么?也许关于Vue路由器?

测试设置:

import { mount } from "@cypress/vue";
import ProductListContainer from "./ProductListContainer.vue";

it("renders a message", () => {
  mount(ProductListContainer);
...
});

模板:

<template>
 //...
 <template #pagination>
    <nav-pagination 
    :page-count="meta ? meta.pageCount : 0"
    :route-query="$route.query"
    />
 </template
</template>

错误:


TypeError
Cannot read property 'query' of undefined 

控制台日志行:

....
 "route-query": _ctx.$route.query

4

1 回答 1

1

Cypress repo中有一个使用 vue 路由器的示例应用程序。

这是他们设置的方式

import PizzaShop from './PizzaShop'           // component to test
import router from './PizzaShop/router'       // router config from app
import { mountCallback } from '@cypress/vue'  // extended mount function

describe('Vue Router - Pizza Shop', () => {

  // your component will be a child of the simple wrapper below
  const extensions = {
    plugins: [router],
    components: {
      PizzaShop,
    },
  }

  // wrapper into which router is injected
  const template = '<router-view />'    

  // initialize a fresh Vue app before each test (equivalent to createLocalVue)
  beforeEach(mountCallback({ template, router }, { extensions }))

  it('go to order page', () => {
    cy.get('button.order').click()
    cy.contains('Toppings')
  })

并且/PizzaShop/router(但是您的应用程序将拥有自己的路由器代码,因此请替换它)

import { createRouter, createWebHashHistory } from 'vue-router'
import PizzaShop from './index.vue'
import Home from './Home.vue'
import Order from './Order.vue'

export default createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      component: PizzaShop,
      children: [
        { path: '', name: 'home', component: Home },
        { path: 'order/:preset?', name: 'order', component: Order },
      ],
    },
  ],
})
于 2022-02-02T21:08:51.627 回答