【问题标题】:Unable to properly mock API calls using Jest无法使用 Jest 正确模拟 API 调用
【发布时间】:2021-09-05 05:20:10
【问题描述】:

我一直在尝试使用 jest.mock() 模拟我的 api,但我什至无法正常调用这些 api。

我已经能够成功地模拟函数,然后像这样模拟 api:

wrapper.vm.getUser = jest.fn(() => Promise.resolve({}));

但我想直接模拟api/authApis.js 中的所有api,而不是在函数中拦截它们。

我不能这样做,因为this.$apis 显示为未定义。

如何使用 Jest 访问和调用 this.$apis.getUser()?

测试/header.spec.js

import { mount } from "@vue/test-utils";
import Header from "../components/Header.vue";

describe("Header", () => {
  it("returns the val from api", async () => {
    //setting multiUser true so button is visible
    const multiUsers = true;
    const wrapper = mount(Header, {
      propsData: {
        multiUsers
      }
    });


    console.log(wrapper.vm.getUser());

    const changeUsrBtn = wrapper.find("#btnChangeUser");
    //triggering the user btn with a click
    changeUsrBtn.trigger("click");
    expect(wrapper.find("button").text()).toBe("Change User");
    expect(wrapper.vm.getUser()).toHaveReturned();    
  });
});

错误:

FAIL  __tests__/header.spec.js
Header
  × returns the val from api (122 ms)

● Header › returns the val from api

  expect(received).toHaveReturned()

  Matcher error: received value must be a mock function

  Received has type:  object
  Received has value: {}

    23 |     expect(wrapper.find("button").text()).toBe("Change User");
    24 |
  > 25 |     expect(wrapper.vm.getUser()).toHaveReturned();
       |                                    ^
    26 |
    27 |   });
    28 | });

    at Object.<anonymous> (__tests__/header.spec.js:25:36)
    at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
    at runJest (node_modules/@jest/core/build/runJest.js:387:19)
    at _run10000 (node_modules/@jest/core/build/cli/index.js:408:7)
    at runCLI (node_modules/@jest/core/build/cli/index.js:261:3)

console.error
  TypeError: Cannot read property 'authService' of undefined

组件/Header.vue

    async getUser() {
      this.showUserLoader = true;
      try {
        const {
          data: { userList }
        } = await 
        this.$apis.authService.getUser();
        this.$store.dispatch("auth/updateUsers", UserList);
      } catch (error) {
        console.error(error);
      } finally {
        this.showUserLoader = false;
      }
    }
...

api/authApis.js(我想模拟整个文件):

export default $axios => ({
  getUser() {
    return $axios({
      url_instance: authInstance,
      method: "get",
      url_suffix: "/sc/typesOfUser",
    });
  },
  changeUser() {
    return $axios({
      url_instance: authInstance,
      method: "post",
      url_suffix: "/sc/changeUser"
    });
  },
...
})

【问题讨论】:

  • 我认为更重要的问题是您如何首先设置this.$apis? :)

标签: javascript vue.js jestjs nuxt.js vue-test-utils


【解决方案1】:

这取决于你如何设置全局this.$api,但如果你想模拟整个文件(尤其是使用默认导出),你应该使用__esModule 属性:

jest.mock('./esModule', () => ({
  __esModule: true, // this property makes it work
  default: 'mockedDefaultExport',
  namedExport: jest.fn(),
}));

更多关于Jest mock default and named export的解释。

【讨论】:

  • 谢谢安德烈。我在我的插件中设置 this.$api。必须弄清楚如何让插件与 Jest 一起工作
猜你喜欢
  • 2019-08-04
  • 1970-01-01
  • 1970-01-01
  • 2019-02-03
  • 2021-11-06
  • 2022-06-30
  • 2020-11-06
  • 2021-12-01
  • 2019-10-03
相关资源
最近更新 更多