How to mock a async function in pinia store testing with vitest

Viewed 27

I'm using vue3+typescript+pinia. I am trying to follow the docs to crete tests but no success, got errors.

I want to test a store action which uses function that returns a promise.

EDITED:

The store pinia action

actions: {
    async createContact(contact: Contact) {
        console.log('this', this);
        
        this.isLoading = true
        ContactDataService.createContact(contact)
            .then(response => {
                this.sucess = true
                console.log(response)
            })
            .catch(error => {
                this.hasError = true
                console.log(error);
            })
        this.isLoading = false
    },
},

The exported class instance:

import Contact from "@/types/ContactType";
import http from "../http-commons";

class ContactDataService {
    createContact(contact: Contact): Promise<any> {
        const headers = {
            "Content-Type": "application/json",
            "accept": "*/*",
            "Access-Control-Allow-Origin": "*"
        }
        return http.post("/contact", contact, { headers });
    }
}

export default new ContactDataService();

The test:

import { setActivePinia, createPinia } from 'pinia'
import { describe, it, expect, beforeEach, vi } from "vitest";
import { useContactStore } from '@/stores/ContactStore'
import ContactDataService from "../../services/ContactDataService"
import Contact from '@/types/ContactType';

  vi.mock('../../services/ContactDataService', () => {
    const ContactDataService = vi.fn()
    ContactDataService.prototype.createContact = vi.fn()
    return { ContactDataService }
  })

const contactExample: Contact = {
    firstName: 'string',
    lastName: 'string',
    emailAddress: 'string',
}

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

  it('createContact', async () => {
    const contactStore = useContactStore()
    // expect(contactStore.sucess).toBeFalsy() 
    contactStore.createContact(contactExample)
   // expect(contactStore.sucess).toBeTruthy()
  })
})

When I run test I cant figure out how to mock the ContactDataService.createContact(contact) inside the action createContact.

Error: [vitest] No "default" export is defined on the "mock:/src/services/ContactDataService.ts"

0 Answers
Related