I'm trying to write my first unit test for a VueJS component that grabs some data from an API endpoint when it renders:
My VueJS component:
import axios from 'axios';
export default {
props: {
userIndexUrl: {
required: true
}
},
data() {
userList: [],
tableIsLoading: true
},
created() {
const url = this.userIndexUrl;
axios.get(url)
.then(response => {
this.userList = response.data.data;
this.tableIsLoading = false;
})
},
}
and my test:
import { mount } from 'vue-test-utils'
import moxios from 'moxios'
import UsersAddRemove from 'users_add_remove.vue'
describe('UsersAddRemove', () => {
const PROPS_DATA = {
userIndexUrl: '/users.json'
}
beforeEach(() => {
moxios.install();
moxios.stubRequest('/users1.json', {
status: 200,
response: {
"count": 1,
"data": [
{ "id" : 1,
"email" : "brayan@schaeferkshlerin.net",
"first_name" : "Kenneth",
"last_name" : "Connelly"
}
]
}
});
});
afterEach(() => {
moxios.uninstall();
});
it('loads users from remote JSON endpoint and renders table', () => {
const wrapper = mount(UsersAddRemove, { propsData: PROPS_DATA });
moxios.wait(() => {
expect(wrapper.html()).toContain('<td class="">brayan@schaeferkshlerin1.net</td>');
done();
});
});
});
So what I expect to happen is the component gets instantiated, after which it does an API call, which is caught by Moxios, after which it should execute moxios.wait
, which isn't happening. The tests seem to ignore moxios.wait
, and it passes successfully even when it shouldn't.
What am I missing here?
Try adding the done
as argument:
it('loads users from remote JSON endpoint and renders table', (done) => {
// -----------------------------------------------------------^^^^^^
const wrapper = mount(UsersAddRemove, { propsData: PROPS_DATA });
moxios.wait(() => {
expect(wrapper.html()).toContain('<td class="">brayan@schaeferkshlerin1.net</td>');
done();
});
});
Change as follows:
// remove the stubRequest of beforeEach()
beforeEach(() => {
moxios.install();
});
// afterEach stays the same
it('loads users from remote JSON endpoint and renders table', (done) => {
const wrapper = mount(UsersAddRemove, { propsData: PROPS_DATA });
moxios.wait(() => {
let request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: {
"count": 1,
"data": [{
"id": 1,
"email": "brayan@schaeferkshlerin.net",
"first_name": "Kenneth",
"last_name": "Connelly"
}]
}
}).then(function() {
expect(wrapper.html()).toContain('<td class="">brayan@schaeferkshlerin1.net</td>');
done();
});
});
});