使用vue-cli对vue组件进行单元测试,无法测试父方法?

时间:2018-10-16 08:56:12

标签: javascript unit-testing vue.js vuejs2 vue-cli

我遇到了一个无法解决的问题,环顾四周似乎找不到任何人问同样的问题...

所以,这是我的工作代码:

main.js:

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

window.Vue = Vue

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  methods: {
    greetings: function () {
      return 'good morning'
    }
  },
  render: h => h(App)
})

router / index.js:

import Vue from 'vue'
import Router from 'vue-router'
import Configurations from '@/components/Configurations'

Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/configs',
      name: 'Configurations',
      component: Configurations
    }
  ]
})

App.vue:

<template>
    <router-view></router-view>
</template>
<script>
export default {
  name: "App"
};
</script>

Configurations.vue:

<template>
<span>{{greetings}}</span>
</template>

<script>
export default {
  name: "configurations",
  data() {
    return {
      greetings: ""
    };
  },
  created: function() {
    this.greetings = this.$root.greetings();
  }
};
</script>

运行此命令时,它会显示一个页面,上面写着“早上好”。没有其他的。如您所见,问候消息是在main.js文件上定义的,因为在这种情况下,我希望在所有组件上都显示一条消息,即:版权说明。因此,我在所有祖先的共同祖先上设置了消息。

据我了解,要从“父”组件中调用方法,请使用this。$ root.yourMethod()进行调用。

现在,问题是,如果我希望为配置组件运行单元测试,则会收到一个错误,该错误使我相信我已经设置了东西的方式无法测试this。$ root .greetings(),因为有些东西告诉我测试环境并未意识到组件之间的父子关系。

所以,当我跑步时:

cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run

已设置以下测试文件:

Configurations.spec.js

import Configurations from '@/components/Configurations'
import Vue from 'vue'

describe('Configurations.vue', () => {
  it('should display a greetings message', () => {
    const Constructor = Vue.extend(Configurations)
    const ConfigurationsComponent = new Constructor().$mount()
    expect(ConfigurationsComponent.greetings).to.not.be.undefined;
  })
})

我得到:

> 16 10 2018 09:28:35.184:INFO [karma]: Karma v1.7.1 server started at
> http://0.0.0.0:3000/ 16 10 2018 09:28:35.191:INFO [launcher]:
> Launching browser PhantomJS with unlimited concurrency 16 10 2018
> 09:28:35.204:INFO [launcher]: Starting browser PhantomJS 16 10 2018
> 09:28:40.977:INFO [PhantomJS 2.1.1 (Windows 8.0.0)]: Connected on
> socket WnDl-mQqmNZQOfyzAAAA with id 10303480 ERROR LOG: '[Vue warn]:
> Error in created hook: "TypeError:  is not a constructor (evaluating
> 'this.$root.greetings()')"

(紧随其后的是更多行,由于它们包含太多链接,因此堆栈溢出不会让我发帖)

现在,如果我要更改

this.greetings = this.$root.greetings()

收件人:

this.greetings = "good morning";

Configurations.vue 文件中,然后再次运行测试命令,我将得到:

> 16 10 2018 09:48:43.174:INFO [karma]: Karma v1.7.1 server started at
> http://0.0.0.0:3000/ 16 10 2018 09:48:43.180:INFO [launcher]:
> Launching browser PhantomJS with unlimited concurrency 16 10 2018
> 09:48:43.555:INFO [launcher]: Starting browser PhantomJS 16 10 2018
> 09:48:49.228:INFO [PhantomJS 2.1.1 (Windows 8.0.0)]: Connected on
> socket o8BQ24wv1QX26SAZAAAA with id 53463701
> 
>   Configurations.vue
>     √ should display a greetings message
>
> PhantomJS 2.1.1 (Windows 8.0.0): Executed 1 of 1 SUCCESS (0.024 secs / 0.017 secs)
>
> TOTAL: 1 SUCCESS

(后面还有其他不相关的信息)

那么,如何为包含对this。$ root方法的调用的组件运行单元测试?

感谢您的帮助。

  • 卢卡斯

1 个答案:

答案 0 :(得分:0)

您应该(几乎)永远不要从父组件中调用任何东西。

您有2种可能性: 1.使用vuex存储并将数据保存在那里。这样,每个需要的组件都可以通过商店获取器访问它。 2.将所需数据作为道具提供给子组件。

因为道具东西变得非常凌乱,所以建议使用商店。

如果这样做,您的测试将变得更加清晰和易于阅读。

使用模拟商店的简单测试(只是为了说明情况如何):

describe('MyComponent', () => {
  let wrapper

  beforeEach(() => {
    const localVue = createLocalVue()
    wrapper = mount(MyComponent, {
      localVue,
      mocks: {
        $store: {
          getters: {
            'copyright': 'MyCopyright text'
          }
        }
      }
    })
  })

  it('should display copyright text', () => {
    expect(wrapper.text('MyCopyright text')).toBe(true) 
  })
})