如何测试 return 承诺的嵌套 vuex 操作?

How to test nested vuex actions that return promises?

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

// 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 到 return 成为一个已解决的承诺,那将在turn 触发组件上 then 方法下的下一次调用。但它不是。

我应该如何测试是否确实调用了 Vuex 操作?

如果有意义的话,我愿意接受多个测试而不是一个测试的想法。或者甚至将 3 个调用重构为其他东西,只要它们在成功时按该顺序调用即可。

谢谢!

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

这是经过测试的更新组件。

// 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)
  })
})

希望对大家有所帮助!