【问题标题】:Mock .get() Function using Jest on VueJS在 VueJS 上使用 Jest 模拟 .get() 函数
【发布时间】:2021-03-31 06:20:30
【问题描述】:

我正在尝试模拟 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

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

【问题讨论】:

    标签: vue.js jestjs ts-jest jest-fetch-mock


    【解决方案1】:

    假设您在Post 组件的methods 中定义了getPost(),则不能使用命名导入来访问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(...)
    })
    

    还要确保在getPost() 中返回axios 调用,以便它可以是awaited:

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

    【讨论】:

    • 您好,非常感谢您!我已将其更改为 it('should return empty when axios.get failed', async () => { const wrapper = shallowMount(Post) await wrapper.vm.getPost() const getError = new Error('error'); axios.get = jest.fn().mockRejectedValue(getError); expect(wrapper.vm.post).toEqual("undefined"); expect(axios.get).toBeCalledWith('/posts/postid'); }); 但我收到错误 TypeError: Cannot read property 'get' of undefined。我不知道为什么会这样?
    猜你喜欢
    • 2021-03-17
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2018-10-26
    • 2019-07-22
    • 2022-06-29
    相关资源
    最近更新 更多