【发布时间】:2021-01-25 22:15:59
【问题描述】:
功能: (更新:由于其他代码我需要它是异步/等待,否则我的其他代码不起作用)
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
我尝试过承诺、moxios、sinon,但似乎没有任何效果。当我在函数中记录this.all 时,它具有正确的值。但是,在测试中,它不会等待函数完成并将值分配给this.all。我试过nextTick,flushPromises,await。如何让测试等到函数getAll() 分配了this.all 响应数据?提前谢谢你。
【问题讨论】:
-
在模拟调用之后不应该发生刷新吗?
-
之前的刷新是针对我在mounted()中的异步函数,但我也尝试在调用getall()之前和之后添加刷新