【问题标题】:Testing vuex action that contains an async测试包含异步的 vuex 操作
【发布时间】:2017-12-11 21:44:26
【问题描述】:

[这是一个Vue应用,使用Vuex,使用vue-cli创建,使用mocha、chai、karma、sinon]

我正在尝试为我的 vuex 状态创建测试,我不想使用模拟 - 我对这些测试的一大目标是同时测试数据来自的 API。

我正在尝试遵循 chai-as-promised 的文档。

这是我正在尝试测试的 vuex 操作的简化:

const actions = {
  login: (context, payload) => {
    context.commit('setFlashMessage', "");
    axios.get("https://first-api-call")
      .then((response) => {
        axios.post("https://second-api-call")
          .then((response) => {
            router.push({ name: "Home"});
            context.commit('setFlashMessage', "Logged in successfully");
            context.commit('setLogin', response.data);
        });
    },

请注意,登录操作有两个承诺,并且不返回任何内容。登录操作做了两件事:设置一些状态并更改路由。

我看到的使用 chai-as-promised 的示例期望返回承诺。那就是:

var result = systemUnderTest();
return expect(result).to.eventually.equal(blah);

但就我而言,login() 不会返回任何内容,而且我不确定如果返回的话我会返回什么。

这是我目前所拥有的:

import store from '@/src/store/store'
describe('login', () => {
  it('bad input', () => {
    store.login({ username: "abcd", password: ""});
    // What is the test I should use?
  }
}

【问题讨论】:

    标签: unit-testing vuejs2 chai vuex chai-as-promised


    【解决方案1】:

    我会返回登录响应消息并进行两个测试。一个确保无效凭据返回失败消息,另一个确保有效凭据成功登录

    【讨论】:

      【解决方案2】:

      我和我的同事想出了解决方案:

      vuex action需要返回promise,可以链接在一起:

      login: (context, payload) => {
          context.commit('setFlashMessage', "");
          return axios.get("https://first-api-call")
              .then((response) => {
                  return axios.post("https://second-api-call")
              })
              .then((response) => {
                  // etc...
                  router.push({ name: "Home"});
                  context.commit('setFlashMessage', "Logged in successfully");
                  context.commit('setLogin', response.data);
                  return {status: "success"};
              });
      },
      

      然后我们不需要 chai-as-promised 因为测试看起来像这样:

      it('bad password', () => {
          const result = store.dispatch("login", { username: userName, password: password + "bad" });
          return result.then((response) => {
              expect(response).to.deep.equal({ status: "failed"});
              store.getters.getFlashMessage.should.equal("Error logging in");
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-03
        • 2012-05-20
        • 1970-01-01
        • 2017-10-14
        • 2014-02-27
        • 2017-03-04
        相关资源
        最近更新 更多