下面例子中用到的测试可以在 找到。

mutations 易于遵循一套模式:取得一些数据,可能进行一些处理,然后将数据赋值给 state。比如一个 mutation 的概述如下:一旦被实现,它将从 payload 中获取一个 post 对象,并将 post.id 添加到 state.postIds 中;它也会将那个 post 对象以 post.id 为 key 添加到 state.posts 对象中。这即是在应用中使用 Vuex 的一个通常的模式。

我们将使用 TDD 进行开发。mutation 是这样开头的:

  1. import mutations from "@/store/mutations.js"
  2. describe("SET_POST", () => {
  3. it("adds a post to the state", () => {
  4. const post = { id: 1, title: "Post" }
  5. const state = {
  6. postIds: [],
  7. posts: {}
  8. mutations.SET_POST(state, { post })
  9. expect(state).toEqual({
  10. postIds: [1],
  11. posts: { "1": post }
  12. })
  13. })
  14. })

yarn test:unit 运行测试将产生以下错误信息:

让我们从将 post.id 加入 state.postIds 开始:

  1. export default {
  2. state.postIds.push(post.id)
  3. }

现在 yarn test:unit 会产生:

  1. export default {
  2. SET_POST(state, { post }) {
  3. state.postIds.push(post.id)
  4. state.posts = { ...state.posts, [post.id]: post }
  5. }

现在测试都通过了!

测试 Vuex mutations 不需要什么特殊的 Vue 或 Vuex 功能,因为它们都是普通的 JavaScript 函数。根据需要简单地引入它们并测试就行了。唯一需要留意的事情是 Vue 的反应式注意事项,对于 Vuex 也是一样的。更多关于反应式系统和一般注意事项可以在 这里Vuex - Mutations - 图1 读到。

本页讨论了:

  • Vuex mutations 是普通的 JavaScript 函数