Search code examples
vue.jssinonvitest

Is sinon comptible with vitest?


I'm going to migrate to vite and vitest. Now I'm learning how to use vitest and suddenly I found vitest has a problem loading module sinon.

Is sinon compatible with vitest?

When I run the test with 'npm run test:unit', it responds as follows:

FAIL  src/stores/__tests__/counter.spec.ts [ src/stores/__tests__/counter.spec.ts ]
Error: [vite-node] Failed to load sinon
 ❯ async src/stores/__tests__/counter.spec.ts:9:31
      7| describe('useCounterStore', () => {
      8|     beforeEach(() => {
      9|         setActivePinia(createPinia());
       |                               ^
     10|     });
     11| 

I know that vitest suggest using msw to mock request but for now I'd like to give sinon a try since my colleagues are already familiar with sinon.

Here is the test file counter.spec.ts:

import { describe, it, expect, beforeEach } from 'vitest';
import { useCounterStore } from '../counter';
import { setActivePinia, createPinia } from 'pinia';
import axios from 'axios';
import sinon from 'sinon';

describe('useCounterStore', () => {
    beforeEach(() => {
        setActivePinia(createPinia());
    });

    it.skip('Counter Store - increment()', () => {
        const counter = useCounterStore();
        expect(counter.counter).toBe(0);
        counter.increment();
        expect(counter.counter).toBe(1);
    });

    it('getName - axios success', () => {
        const counter = useCounterStore();
        sinon.stub(axios, 'get').resolves({ data: 'abc' });

        counter.getName();

        expect(counter.name).toEqual('abc');
    });
});

And here is the counter.ts (Pinia store)

import axios from 'axios';
import * as pinia from 'pinia';

export const useCounterStore = pinia.defineStore({
    id: 'counter',
    state: () => ({
        counter: 0,
        name: '',
    }),
    getters: {
        doubleCount: state => state.counter * 2,
    },
    actions: {
        increment() {
            this.counter++;
        },
        async getName() {
            const rlt = await axios
                .get('https://jsonplaceholder.typicode.com/todos/1')
                .then((response:any) => response.data)
                .catch(error => console.log(error));
            // console.log(rlt);
            this.name = rlt.data;
        },
    },
});



Solution

  • Finally, I follow 3 Ways To Mock Axios In Jest and chose the #3 way - axios-mock-adapter.

    This would be easier than msw and axios-mock-adapter is more powerful than sinon when I want to mock a http request.