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

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

我正在为分页模块编写单元测试,它有一个简单的 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)
  })
})

最佳答案

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

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

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

关于unit-testing - 为什么 VueX 存储在多个单元测试中保持状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54556952/

相关文章:

unit-testing - 如何在另一个方法中 stub

python - py.test : error: unrecognized arguments: --cov-report --cov=

javascript - 我可以测试函数中的变量吗?

javascript - 查找集合中是否存在具有值的项目

javascript - 如何在 Vue 3 模板中使用导入函数?

perl - 我如何将 Perl 的 'prove' 与其他语言的 TAP 生产者一起使用?

node.js - 在 Node.js 中,如何编写单元测试页面速度?

unit-testing - 使用 NUnit 测试适配器进行单元测试失败,但使用 VS2012 中的 ReSharper 则不会

javascript - 在 construct 2 html Canvas 上禁用点击事件传播

node.js - Mocha,如何忽略 node_modules 文件夹