使用API​​调用测试Vuex操作

时间:2017-06-06 18:27:32

标签: javascript vue.js mocha vuejs2 vuex

我正在尝试测试一个通过API调用获取数据的简单Vuex操作。我弄得最麻烦的是如何模拟那个电话。我现在这样做的方式感觉不对,但我不知道还能去哪里。

我尝试将axios调用抽象为一个服务,使其更类似于Vuex样板,但产生了相同的结果。其余代码与测试操作的Vuex文档相同 - here

动作

//actions.js 

export default {
  getData({ commit }) {
    return axios.get(__API__ + 'test/', {
      headers: auth.getAuthHeader(),
    })
    .then(function (response) {
      commit('getData', response.data);
    })
    .catch(function (error) {
      console.log(error.message);
    });
  },
};

模拟

//actions.spec.js

const url = __API__ + 'test/';
// create the module with our mocks
const actions = actionsInjector({
  url: {
    getData () {
      return new Promise((resolve, reject) => {
        const arr = ['Cat', 'Dog', 'Fish', 'Snail']
        resolve(arr)
      });
    }
  }
});

辅助功能

// utils.js  

const testAction = (action, payload, state, expectedMutations, done) => {
  let count = 0;

  // mock commit
  const commit = (type, payload) => {
    const mutation = expectedMutations[count];
    try {
      expect(mutation.type).to.equal(type);
      if (payload) {
        expect(mutation.payload).to.deep.equal(payload);
      }
    } catch (error) {
      done(error);
    }

    count++;
    if (count >= expectedMutations.length) {
      done();
    }
  }

  // call the action with mocked store and arguments
  action({ commit, state }, payload);

  // check if no mutations should have been dispatched
  if (expectedMutations.length === 0) {
    expect(count).to.equal(0);
    done();
  }
}

export default testAction;

测试用例

// actions.spec.js

it('it has an action that gets data', done => {
  testAction(actions.getData, [], {}, [
    { type: 'getData',  payload: ['Cat', 'Dog', 'Fish', 'Snail'] }
  ], done)
});

error: undefined is not a constructor (evaluating 'action({ commit: commit, state: state }, payload)')
testAction@index.js:19858:9
index.js:19813:25

0 个答案:

没有答案