Explorar o código

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

* assert dispatched type

* add [vuex] label in assertion error message
katashin %!s(int64=8) %!d(string=hai) anos
pai
achega
81217dd18a
Modificáronse 2 ficheiros con 26 adicións e 0 borrados
  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
       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 state = this.state
     if (handler) {

+ 19 - 0
test/unit/test.js

@@ -25,6 +25,25 @@ describe('Vuex', () => {
     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 () {
     const store = new Vuex.Store({
       state: {