【问题标题】:Mocked API response is `undefined` in jest with vue-utils用 vue-utils 开玩笑的 API 响应是“未定义”
【发布时间】:2021-09-24 02:52:14
【问题描述】:

我有一个 Vue 3 应用程序,它进行 API 调用并处理响应以调整一些数据字段。 API 调用是在子组件发出自定义事件后进行的,父组件正在侦听该事件。它工作正常,但现在我想测试(jest 26,vue-test-utils)它,我一直在失败。我无法模拟响应,它总是undefined。因此,我不能指望更改的数据字段。

我是开玩笑的新手,但我认为这是模拟响应的理想方式。还是我错了?

这是我的抽象测试代码。看看open()-method 以及我如何尝试模拟它的 API 响应。

结构:

-
|- Parent.vue
|- Child.vue
|- api.js

父.vue

<template>
  <Child
    v-for="price in prices"
    :key="price.type"
    :price="price"
    @open="open"
  ></Child>
</template>
<script>
// imports
export default {
  name: "Parent",
  components: {
    Child
  },
  props: ["id"],
  async mounted() {
    // on creation load initial prices
    const pricesDto = await loadPricesFor(this.id);
    this.prices = toPrices(pricesDto); // external dto to array mapper
  },
  data() {
    return {
      prices: []
    };
  },
  methods: {
    async open() {
      try {
        const response = await makeApiCall(this.id);
        console.log("foo", response); // response is undefined!
        // make something with response data
      } catch (error) {
        // do nothing
      }
    }
  }
};
</script>

parent.test.js:


import {flushPromises, mount} from "@vue/test-utils";
import * as apiModule from "./api.js";
import Child from "./Child";

jest.mock("./api.js");

it("test api call", async () => {
    // given
    const wrapper = async () => {
        return mount(Child, {
            props: {
                id: "123",
            },
        });
    };
    await flushPromises();

    // when
    wrapper.findComponent(Child).vm.$emit("open");

    // then
    const mockedResponse = {
        foo: "bar",
    };
    const response = Promise.resolve({
        status: 200,
        ok: true,
        json: () => Promise.resolve(mockedResponse),
    });
    const spy = jest.spyOn(apiModule, "makeApiCall").mockReturnValueOnce(response);
    expect(spy).toHaveBeenCalledWith("123");

    // expect changed data fields regarding to response. This is not working!
});

我希望您可以在没有交互式示例的情况下解决它,如果不告诉我,我会编写一些代码。

【问题讨论】:

    标签: javascript vue.js jestjs


    【解决方案1】:

    解决方案:好吧,我很笨。我需要模拟我的响应之前触发自定义事件而不是之后(有意义......)。因此,如果我要搬家,代码会按预期工作

    const spy = jest.spyOn(apiModule, "makeApiCall").mockReturnValueOnce(response);
    

    //when 块之前。

    【讨论】:

      猜你喜欢
      • 2022-10-16
      • 2022-07-12
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2021-09-17
      • 2017-11-01
      • 2018-06-02
      相关资源
      最近更新 更多