为什么 VueX 存储在多个单元测试中保持状态?

Why does VueX store retain state across multiple unit tests?

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

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

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

我曾尝试 return 一个新的分页模块,方法是使用 return 一个 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)
  })
})

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

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

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