首页 文章

如何测试返回promises的嵌套vuex操作?

提问于
浏览
0

这是我的组件中的代码和我当前的测试:

// component script
import { mapActions } from 'vuex'

export default {
  name: 'foo',
  mounted () {
    this.firstMethod()
      .then(() => {
        this.secondMethod()
      })
      .then(() => {
        this.thirdMethod()
      })
  },
  methods: {
    ...mapActions([
      'firstMethod',
      'secondMethod',
      'thirdMethod'
    ])
  }
}

// test
import { shallow, createLocalVue } from 'vue-test-utils'
import Vuex from 'vuex'
import Foo from '../Foo.vue'

const localVue = createLocalVue()

localVue.use(Vuex)

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

  beforeEach(() => {
    actions = {
      firstMethod: sinon.stub().resolves(),
      secondMethod: sinon.stub().resolves(),
      thirdMethod: sinon.stub(),
    }

    store = new Vuex.Store({
      actions
    })

    wrapper = shallow(Foo, { store, localVue })
  })

  it.only('calls store actions when mounted', () => {
    expect(actions.firstMethod.called).toBe(true) // succeedes
    expect(actions.secondMethod.called).toBe(true) // fails
    expect(actions.thirdMethod.called).toBe(true) // fails
  })
})

我期待所有三个 expects 成功,因为我知道 .resolves() 方法使 stub 返回一个已解决的promise,而这将依次触发组件上 then 方法下的下一个调用 . 但事实并非如此 .

我该如何测试Vuex操作确实被调用?

如果这是有意义的话,我愿意接受多次测试的想法,而不只是一次 . 甚至将3个调用重构为其他内容,只要在成功时按顺序调用它们 .

谢谢!

1 回答

  • 0

    好的,所以我改变了组件安装方法的结构,但测试也适用于原始代码 .

    这是测试的更新组件 .

    // component script
    import { mapActions } from 'vuex'
    
    export default {
      name: 'foo',
      mounted () {
        this.mount()
      },
      methods: {
        async mount () {
          await this.firstMethod()
          await this.secondMethod()
          await this.thirdMethod()
        },
        ...mapActions([
          'firstMethod',
          'secondMethod',
          'thirdMethod'
        ])
      }
    }
    
    // test
    import { shallow, createLocalVue } from 'vue-test-utils'
    import Vuex from 'vuex'
    import Foo from '../Foo.vue'
    
    const localVue = createLocalVue()
    
    localVue.use(Vuex)
    
    describe('Foo.vue', () => {
      let actions
      let store
      let wrapper
    
      beforeEach(() => {
        actions = {
          firstMethod: sinon.stub().resolves(),
          secondMethod: sinon.stub().resolves(),
          thirdMethod: sinon.stub().resolves()
        }
    
        store = new Vuex.Store({
          actions
        })
    
        wrapper = shallow(Foo, { store, localVue })
      })
    
      it('calls store actions when mounted', async () => {
        await expect(actions.firstMethod.called).toBe(true)
        await expect(actions.secondMethod.called).toBe(true)
        await expect(actions.thirdMethod.called).toBe(true)
      })
    })
    

    我希望这可以帮助别人!

相关问题