微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 VueJS 上使用 Jest 模拟 .get() 函数

如何解决在 VueJS 上使用 Jest 模拟 .get() 函数

我正在尝试模拟 GET 请求以使用 ID 获取一些帖子。这是我试图模拟的代码

getPost() {
  this.refreshToken();
  http
    .get(`/posts/${this.$cookie.get('postid')}`,{
      headers: {
        "Authorization": `Bearer ${this.$cookie.get('token')}`,"Content-type": "application/json",},})
    .then((response) => {
      this.post = response.data;
    })
    .catch((error) => {
      console.log(error.response);
    });
}

这是我的测试尝试:

import {getPost} from '@/views/Post.vue'
import axios from 'axios';

jest.mock('axios');

describe('get Post by ID',() => {
  afterEach(() => {
    jest.resetAllMocks();
  });

  it('should return empty when axios.get Failed',async () => {
    const getError = new Error('error');
    axios.get = jest.fn().mockRejectedValue(getError);
    const actualValue = await getPost();
    expect(actualValue).toEqual(new Map());
    expect(axios.get).toBeCalledWith('/posts/postid');
  });

  it('should return users',async () => {
    const mockedUsers = [{ postID: 1 }];
    axios.get = jest.fn().mockResolvedValue(mockedUsers);
    const actualValue = await getPost(['1']);
    expect(actualValue).toEqual(mockedUsers);
    expect(axios.get).toBeCalledWith('/posts/postid');
  });
})

我得到的错误是:

TypeError: (0,_Post.getPost) is not a function

我不知道该怎么做,任何帮助将不胜感激。谢谢!

解决方法

假设您在 getPost() 组件的 Post 中定义了 methods,您不能使用命名导入来访问 getPost。相反,您必须安装组件,并使用 wrapper's vm:

// Post.spec.js
import { shallowMount } from '@vue/test-utils'
import Post from '@/views/Post.vue'

it('...',() => {
  const wrapper = shallowMount(Post)
  await wrapper.vm.getPost()
  expect(wrapper.vm.post).toEqual(...)
})

还要确保在 axios 中返回 getPost() 调用,以便它可以被await编辑:

// Post.vue
export default {
  methods: {
    getPost() {
      this.refreshToken();
        ?
      return http.get(/*...*/)
        .then(/*...*/)
        .catch(/*...*/);
    }
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?