Answer the question
In order to leave comments, you need to log in
How to replace the api call in vuex actions when testing with SinonJs?
// @/api/index.js
import axios from 'axios';
export const storeTask = function(payload) {
return axios.post(`/tasks`, payload);
};
// @/store/actions.js
import * as api from '../api';
export const saveTask = ({ commit, state }) => {
if (!state.task.body) {
commit('setMessage', 'Please enter a task');
return;
}
return api.storeTask({ body: state.task.body }).then(res => {
commit('prependToTasks', res.data);
commit('setMessage', 'Task saved');
commit('setTask', null);
});
};
// tests/unit/actions.spec.js
import { state as initialState } from '@/store';
import sinon from 'sinon';
import { expect } from 'chai';
import * as actions from '@/store/actions'
describe('ACTIONS', () => {
it('saveTask if a task has not been entered', () => {
const state = {...initialState};
const commit= sinon.spy();
actions.saveTask({commit, state});
expect(commit.args).to.deep.equal([
['setMessage', 'Please enter a task']
]);
});
it('saveTask if a task has been entered', () => {
const fakedTask = { id: 0, body: 'Test task' };
const state = {...initialState};
const commit= sinon.spy();
state.task.body = fakedTask.body;
actions.saveTask({ commit, state });
// тест
});
});
expect(commit.args).to.deep.equal([
['prependToTasks', fakedTask],
['setMessage', 'Task saved'],
['setTask', null]
]);
Answer the question
In order to leave comments, you need to log in
I did it not so long ago, through useFakeXMLHttpRequest;
beforeEach(() => {
const fakeXml = sinon.useFakeXMLHttpRequest();
const requests = (this.requests = []);
fakeXml.onCreate = funciton(xhr) {
request.push(xhr);
}
})
setTimeout(() => {
this.request[0].responde(200, data);
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question