浏览代码

[v1.0] Assert dispatched type (#552)

* assert dispatched type

* add [vuex] label in assertion error message
katashin 8 年之前
父节点
当前提交
81217dd18a
共有 2 个文件被更改,包括 26 次插入0 次删除
  1. 7 0
      src/index.js
  2. 19 0
      test/unit/test.js

+ 7 - 0
src/index.js

@@ -106,6 +106,13 @@ class Store {
       if (type.silent) silent = true
       if (type.silent) silent = true
       type = type.type
       type = type.type
     }
     }
+
+    if (typeof type !== 'string') {
+      throw new Error(
+        `[vuex] Expects string as the type, but found ${typeof type}.`
+      )
+    }
+
     const handler = this._mutations[type]
     const handler = this._mutations[type]
     const state = this.state
     const state = this.state
     if (handler) {
     if (handler) {

+ 19 - 0
test/unit/test.js

@@ -25,6 +25,25 @@ describe('Vuex', () => {
     expect(store.state.a).to.equal(3)
     expect(store.state.a).to.equal(3)
   })
   })
 
 
+  it('throws for dispatch with undefined type', () => {
+    const store = new Vuex.Store({
+      state: {
+        a: 1
+      },
+      mutations: {
+        // Maybe registered with undefined type accidentally
+        // if the user has typo in a constant type
+        undefined (state, n) {
+          state.a += n
+        }
+      }
+    })
+    expect(() => {
+      store.dispatch(undefined, 2)
+    }).to.throw(/Expects string as the type, but found undefined/)
+    expect(store.state.a).to.equal(1)
+  })
+
   it('injecting state and action to components', function () {
   it('injecting state and action to components', function () {
     const store = new Vuex.Store({
     const store = new Vuex.Store({
       state: {
       state: {