用Jest / Moxios模拟Vuex Actions API调用

时间:2018-11-12 12:45:03

标签: unit-testing vue.js axios moxios

我已经使用Moxios来模拟Vue shallowMount ed组件中的API调用而没有问题,但是经过多次尝试,我仍然无法模拟在Vuex Action中进行的Axios API调用...

这是我最小的src/store/actions.js

import axios from "axios";
import queryString from "query-string";

const api = axios.create({
    baseURL: "https://api.example.com/service",
});

export default {
    fetch: function(context, params) {
        context.commit("startLoading");
        api
            .request({
                url: `/endpoint?${queryString.stringify(params)}`,
                method: "get"
            })
            .then(response => {
                context.commit("processResponse", response.data);
            })
            .catch(error => context.commit("errorFlag"))
            .finally(() => context.commit("stopLoading"));
    }
};

还有我的spec文件:

import moxios from "moxios";
import store from "@/store";
import actions from "@/store/actions";
import response from "./mock-data/response.json";

describe("fetch action", () => {
    beforeEach(() => {
        moxios.install();
    });

    afterEach(() => {
        moxios.uninstall();
    });

    it("should fetch its stuff", done => {
        moxios.stubRequest(/endpoint/, {
            status: 200,
            response
        });

        actions.fetch(store, { someparam: "someValue" });

        moxios.wait(() => {
            expect(store.state.results.stuff.length).toBe(response._meta.total)
            done();
        });
    });
});

测试失败,我还收到一条错误消息,例如:

  

console.error node_modules / jsdom / lib / jsdom / virtual-console.js:29错误:未捕获[错误:expect(已接收).toBe(已预期)// Object.is相等,期望值:96   收到:0]

moxios.wait回调被执行,因此startLoading突变也是如此。但是processResponse的{​​{1}}中的api永远不会被调用。

我在Vue组件上使用了相同的测试方法,then()很好用,所以我猜这里的问题是,由于在测试中导入了动作,moxios.stubRequest被创建并且api不能真正捕获和模拟该呼叫,但是我对此不太确定...

我一直在处理其他与SO相关的问题和许多文章,但都没有成功,我无法弄清发生了什么情况,因此任何提示/帮助将不胜感激!

0 个答案:

没有答案