函数:(更新:由于其他代码,我需要它是异步/等待,否则我的其他代码不能工作)
async getAll() {
request_url = "http://localhost:8082/test"
await axios
.get(request_url, {
headers: { 'Access-Control-Allow-Origin': '*' },
})
.then(response => {
this.all= response.data
})
.catch(error => {
this.errorMessage = error.message
})
},测试:
import { mount, shallowMount, createLocalVue } from '@vue/test-utils'
import Map from '@/views/Map'
import Vue from 'vue'
import Vuetify from 'vuetify'
import moxios from 'moxios'
import axios from 'axios'
import flushPromises from 'flush-promises'
jest.mock('axios');
Vue.use(Vuetify)
let vuetify
let wrapper
vuetify = new Vuetify()
const localVue = createLocalVue()
describe('View', () => {
beforeEach(() => {
jest.clearAllMocks();
moxios.install()
wrapper = shallowMount(Map, {
localVue,
vuetify,
})
// I need this because I call another function with axios on mounted
flushPromises()
})
it('should get all', async () => {
axios.get = jest.fn().mockResolvedValue({
data: [
{
test: 'test'
}
]
});
await wrapper.vm.getAll().then(() => {
expect(wrapper.vm.all).toEqual(
test: 'test'
)
})
})结果:
Expected value to equal:
{"test": "test"}
Received:
undefined我试过许诺,用艾灸,用辛农,似乎都不管用。当我在函数中记录this.all时,它的值是正确的。但是,在测试中,它不会等待函数完成,也不会等待将值赋给this.all。我尝试过nextTick,flushPromises,await。如何让测试等待到函数getAll()为this.all分配了响应数据?提前谢谢你。
发布于 2021-01-28 13:43:50
您的方法getAll()应该是promise,因为"axios“是promise并返回promise。
所以..。如果getAll是一个promise,那么接下来可以用.then().catch()调用它。
记住,当所有任务结束时,在你的promise中返回resolve(),或者如果你的promise以错误结束,则返回rejection()。
https://stackoverflow.com/questions/65893174
复制相似问题