【问题标题】:Why does VueX store retain state across multiple unit tests?为什么 VueX 存储在多个单元测试中保留状态?
【发布时间】:2019-06-30 14:27:43
【问题描述】:

我正在为分页模块编写单元测试,它有一个简单的 VueX 存储模块。

我正在使用 Vue.js 2.5 和 Mocha/Chai/Sinon 进行测试。使用 Vue CLI 3 进行设置。

问题是,当currentPage 在一个单元测试中的存储中增加时,即使我尝试创建一个新存储,这种状态也会持续到下一个测试。

我试图通过使用返回Object.assign() 新副本的函数来返回新的分页模块,但这不起作用。我已将其保留在代码中,如下面的规范所示。

store/pagination.js

const state = {
  currentPage: 0
}

export const getters = {
  currentPage: state => {
    return state.currentPage
  }
}

export const actions = {

  nextPage ({ commit, state }) {
    commit('setCurrentPage', state.currentPage + 1)
  }
}

export const mutations = {
  setCurrentPage (state, page) {
    state.currentPage = page
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

Pagination.spec.js

function getPaginationStore () {
  return Object.assign({}, pagination)
}

describe('Paginate.vue', () => {
  let localVue
  let wrapper
  let store

  beforeEach(() => {
    localVue = createLocalVue()
    localVue.use(Vuex)

    store = new Vuex.Store({
      modules: {
        pagination: getPaginationStore()
      }
    })

    wrapper = shallowMount(Pagination, {
      localVue,
      propsData: {
        items: [],
        size: 24
      },
      store
    })
  })

  afterEach(() => {
    store = null
  })

  it('state should be 0', () => {
    expect(wrapper.vm.pageNumber).to.equal(0)
    wrapper.vm.$store.dispatch('pagination/nextPage')
    expect(wrapper.vm.pageNumber).to.equal(1)
  })

  it('state should be 0 again but is 1', () => {
    // THIS TEST FAILS. IT IS ACTUALLY 1
    expect(wrapper.vm.pageNumber).to.equal(0)
  })
})

【问题讨论】:

    标签: unit-testing vue.js mocha.js vuex vue-test-utils


    【解决方案1】:

    解决方案是对模块中的状态使用函数而不是普通的旧 javascript 对象。这是我的新商店状态代码:

    export const state = () => {
      return {
        currentPage: 0
      }
    }
    

    答案由 Vue discord 频道的 @SumNeuron 提供。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      相关资源
      最近更新 更多