O
O
Oleg Timoshenko2018-07-30 09:41:52
Unit testing
Oleg Timoshenko, 2018-07-30 09:41:52

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 });
        // тест
    });
});

How can I replace the api.storeTask call with SinonJs to test as in the first test
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

1 answer(s)
N
Nikita Ronzin, 2021-11-08
@Ababinili

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);
}
})

in it after action do
setTimeout(() => {
this.request[0].responde(200, data);
})

and then check the answer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question