Skip to content

Instantly share code, notes, and snippets.

@aphofstede
Created April 9, 2018 15:30
Show Gist options
  • Save aphofstede/70171aa2d793cbf052168beca47956c0 to your computer and use it in GitHub Desktop.
Save aphofstede/70171aa2d793cbf052168beca47956c0 to your computer and use it in GitHub Desktop.
Reproduction of an issue with a test that tests a debounced async Vue component function
// See https://stackoverflow.com/questions/47907000/testing-debounced-asynchronous-request-with-moxios-and-faketimers
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)
wrapper.vm.$nextTick(() => {
moxios.wait(() => {
try {
// It should have called axios with the right params
let request = moxios.requests.mostRecent()
expect(JSON.parse(request.config.data)).toEqual({param: 'example'})
done()
} catch (e) {
done(e)
}
})
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment