首页 文章

测试包含异步的vuex操作

提问于
浏览
0

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

我正在尝试为我的vuex状态创建测试,我不想使用模拟 - 这些测试的一个重要目标是测试数据来自的API .

我正在尝试按照承诺的方式遵循文档 .

这是我试图测试的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);
        });
    },

请注意,登录操作有两个promise并且不返回任何内容 . 登录操作有两件事:它设置一些状态并改变路由 .

我见过使用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?
  }
}

2 回答

  • 0

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

  • 0

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

    vuex动作需要返回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-promise,因为测试看起来像这样:

    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");
        });
    });
    

相关问题