Home > other >  Vitest, How to mock a function dependency
Vitest, How to mock a function dependency

Time:10-16

I am trying to mock the dependency fn getUser & createAndReturnUser of this snippet without any success:

passport.js

const {getUser, createAndReturnUser} = require('../../../../db/queries');

const verifyCallback = async (accessToken, refreshToken, profile, cb) => {
    // Check if user exists (Find or Create)
    try {
        const responseUser = await getUser(profile.id, profile.provider);
        console.log('Response user',responseUser);
        if (responseUser) {
            return cb(null, responseUser);
        } else {
            const newUser = await createAndReturnUser(
                profile.id,
                profile.displayName,
                profile.name.givenName,
                profile.name.middleName,
                profile.name.familyName,
                profile.emails[0].value,
                profile.photos[0].value,
                profile.provider,
                accessToken,
                refreshToken
            )
            return cb(null, newUser);
        }
    } catch (err) {
        return cb(err);
    }
}

passport.test.js

import { describe, expect, it, vi } from 'vitest';
import queries from '../../db/queries';

vi.mock('../../db/queries');

describe('verifyCallback() functionality', () => {
        it('should verify an existing user', async () => {
            const accessToken = '1234';
            const refreshToken = '1234';
            const profile = {
                id: '12345',
                displayName: 'Fake Tech Exec',
                name: {
                    givenName: 'Fake',
                    middleName: 'Tech',
                    familyName: 'Exec'
                },
                emails: [{ value: '[email protected]' }],
                photos: [{ value: 'https:faketechexec.jpg' }],
                provider: 'facebook',
            };

            const cb = vi.fn();

            const user = {
                id: '12345',
                displayName: 'fakeTechExec',
                firstName: 'fake',
                middleName: 'Tech',
                lastName: 'Exec',
                profilePicture: 'faketechexec.jpg'
            }

            queries.getUser.mockResolvedValue(user)

            await verifyCallback(accessToken, refreshToken, profile, cb);
            expect(cb).toBeCalled();
            expect(cb).toBeCalledWith(null, user);
        });
    });

I have been following this guide without any success: https://www.strv.com/blog/quickest-simplest-way-mocking-module-dependencies-jest-engineering

Unfortunately, my test failed and my getUser gets called in the process, throwing an ugly error

  • Related