vue.js - 在 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
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(/*...*/);
}
}
}
推荐阅读
- php - 有条件地删除单个页面的 Storefront 手持菜单
- ios - 不能在 Swift 中同时关闭多个 ViewController
- python - 在 Python 中 Base64 解码此字符串时如何避免“不正确的填充”错误
- spring - Spring Security Filter 链每个请求执行两次。为什么?
- php - 从另一个数组值创建一个数组
- javascript - 在 Dynamics CRM 中将 Javascript 或 CSS 添加到 KnowledgeArticle
- mongodb - 填充虚拟字段时的猫鼬最终一致性
- javascript - 如何从循环中返回值。js, Vue.js
- node.js - Sequelize 无密码查询日志
- android - Kotlin 中这个简单的 var 赋值有什么问题?