功能: (更新:因为其他代码我需要它是 async/await,否则我的其他代码不起作用)
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
我尝试过 promise、moxios 和 sinon,但似乎没有任何效果。当我在函数中记录 this.all
时,它具有正确的值。但是,在测试中,它不会等待函数完成并将值分配给 this.all
。我尝试了 nextTick
、flushPromises
、await
。如何让测试等到函数 getAll()
分配了 this.all
响应数据?提前致谢。
答案 0 :(得分:0)
你的方法 getAll() 应该是一个承诺,因为“axios”是并返回一个承诺。
所以..如果getAll是一个promise,你可以用.then().catch()..
记住在每次任务结束时返回 resolve() 或在 promise 以错误结束时返回rejection()。