Vue.js + Avoriaz:如何测试观察者?

时间:2017-09-21 08:29:45

标签: unit-testing vue.js avoriaz

我正在尝试测试以下组件w Avoriaz,但在道具更改后,观察中的操作:{}未触发

ItemComponent.vue
    switch checkbox
      ✗ calls store action updateList when item checkbox is switched
        AssertionError: expected false to equal true
            at Context.<anonymous> (webpack:///test/unit/specs/components/ItemComponent.spec.js:35:47 <- index.js:25510:48)

感谢您的反馈

ItemComponent.vue

    <template>
      <li :class="{ 'removed': item.checked }">
        <div class="checkbox">
          <label>
            <input type="checkbox" v-model="item.checked"> {{ item.text }}
          </label>
        </div>
      </li>
    </template>

    <script>
      import { mapActions } from 'vuex'
      export default {
        props: ['item', 'id'],
        methods: mapActions(['updateList']),
        watch: {
          'item.checked': function () {
            this.updateList(this.id)
          }
        }
      }
    </script>

这是我的组件测试

ItemComponent.spec.js

    import Vue from 'vue'
    import ItemComponent from '@/components/ItemComponent'
    import Vuex from 'vuex'

    import sinon from 'sinon'
    import { mount } from 'avoriaz'

    Vue.use(Vuex)

    describe('ItemComponent.vue', () => {
      let actions
      let store

      beforeEach(() => {
        actions = {
          updateList: sinon.stub()
        }
        store = new Vuex.Store({
          state: {},
          actions
        })
      })

      describe('switch checkbox', () => {
        it('calls store action updateList when item checkbox is switched', () => {
          const id = '3'
          const item = { text: 'Bananas', checked: true }
          const wrapper = mount(ItemComponent, { propsData: { item, id }, store })
          // switch item checked to false
          wrapper.setProps({ item: { text: 'Bananas', checked: false } })
          expect(wrapper.vm.$props.item.checked).to.equal(false)
          expect(actions.updateList.calledOnce).to.equal(true)
        })
      })
    })

2 个答案:

答案 0 :(得分:0)

U误认为道具,使用:检查

答案 1 :(得分:0)

我应该在$ nextTick块中写下我的期望(actions.updateList()。

  describe('switch checkbox', () => {
    it('calls store action updateList when item checkbox is switched', (done) => {
      const id = '3'
      const item = { text: 'Bananas', checked: true }
      const wrapper = mount(ItemComponent, { propsData: { item, id }, store })
      // switch item.checked to false
      wrapper.setProps({ item: { text: 'Bananas', checked: false } })
      expect(wrapper.vm.$props.item.checked).to.equal(false)
      wrapper.find('input')[0].trigger('input')
      wrapper.vm.$nextTick(() => {
        expect(actions.updateList.calledOnce).to.equal(true)
        done()
      })
    })
  })

然后我的测试没问题

 ItemComponent.vue
    switch checkbox
      ✓ calls store action updateList when item checkbox is switched