【发布时间】:2018-06-03 01:41:48
【问题描述】:
我正在尝试在去抖动方法中测试 axios 调用,但如果我添加假计时器,moxios.wait() 总是会超时。 如果去抖时间设置得足够小(例如 10 毫秒),则测试可以在没有时钟的情况下进行,但这无助于测试正确的去抖。 我已经尝试过使用 Vue.nextTick 进行试验,以及对 it() 的回调进行异步处理,但我似乎只是更深入地研究了杂草。这里的正确方法是什么?
这是一个组件和测试合二为一,显示了问题:
import Vue from 'vue'
import { mount } from 'vue-test-utils'
import axios from 'axios'
import moxios from 'moxios'
import _ from 'lodash'
import expect from 'expect'
import sinon from 'sinon'
let Debounced = Vue.component('Debounced',
{
template: `<div><button @click.prevent="fetch"></button></div>`,
data() {
return {
data: {}
}
},
methods: {
fetch: _.debounce(async () => {
let data = await axios.post('/test', {param: 'example'})
this.data = data
}, 100)
}
}
)
describe.only ('Test axios in debounce()', () => {
let wrapper, clock
beforeEach(() => {
clock = sinon.useFakeTimers()
moxios.install()
wrapper = mount(Debounced)
})
afterEach(() => {
moxios.uninstall()
clock.restore()
})
it ('should send off a request when clicked', (done) => {
// Given we set up axios to return something
moxios.stubRequest('/test', {
status: 200,
response: []
})
// When the button is clicked
wrapper.find('button').trigger('click')
clock.tick(100)
moxios.wait(() => {
// It should have called axios with the right params
let request = moxios.requests.mostRecent()
expect(JSON.parse(request.config.data)).toEqual({param: 'example'})
done()
})
})
})
【问题讨论】:
-
相关moxios问题:github.com/axios/moxios/issues/12
标签: vue.js axios sinon moxios vue-test-utils