Mock a ESM function using Jest in Apollo Server tests

Mock a ESM function using Jest in Apollo Server tests


0

I am trying to setup my integration tests in Apollo Server 4 using Jest and typescript

In my resolver code I have a function checkIfAuthorized which validates if a user has certain access.
I am trying to mock this function and always return me a particular value

I have a folder src/tests/integration
where my integration.spec.ts looks like this

import {ApolloServer} from "@apollo/server";

import {readFileSync} from 'fs';
const typeDefs = readFileSync('./schema.graphql', {encoding: 'utf-8'});
import {resolvers} from "../../resolvers/resolvers.js";
import {jest} from "@jest/globals";
import {AuthService} from "../../utils/authorization";

jest.mock('../../utils/authorization');

describe('Your test suite description', () => {
   
    let authorization: AuthService;

    beforeEach(async () => {
        console.log("In before each ")
        authorization = new AuthService(
    });

    it('returns hello with the provided name', async () => {
        const checkIfAuthorizedMock = jest.spyOn(authorization, 'checkIfAuthorized');
        checkIfAuthorizedMock.mockResolvedValue(await Promise.resolve());

        const testServer = new ApolloServer({
            typeDefs,
            resolvers,
        });
        
        const response = await testServer.executeOperation({
            query: `
      mutation addUser($userId: String!) {
        addUser(
          ....
      }
    `,
            variables: {
                userId: "1234",
            },
            operationName: 'AddUser'
        },);

        console.log("Response " + JSON.stringify(response))

    });
});

This does not mock the checkIfAuthorized function at all, when the resolver is invoked it calls the original method & not the mocked one.
What am I doing wrong?

my src/utils/authorization.ts

export class AuthService {
    async checkIfAuthorized(context?: MyContext, userId?: string) {
     ...
}

my src/resolvers/resolver.ts

export const addUserResolver = async (_parent: any, args: { input: AddUser },
                                                     _context: MyContext
): Promise<User> => {
    try {
        await authorization. checkIfAuthorized(_context, args.input.userId)
        return await some_func()
    } catch (err) {
       
    }
}

This is my tsconfig.json

{
  "compilerOptions": {
    "rootDirs": ["src"],
    "outDir": "dist",
    "lib": ["es2020"],
    "target": "es2020",
    "strict": true,
    "module": "esnext",
    "noErrorTruncation": true,
    "preserveConstEnums": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "types": ["node", "jest"],
  },
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  },

jest-config

import type { JestConfigWithTsJest } from 'ts-jest'

const jestConfig: JestConfigWithTsJest = {
    // [...]
    extensionsToTreatAsEsm: ['.ts'],
    moduleNameMapper: {
        '^(\.{1,2}/.*)\.js$': '$1',
    },
    transform: {
        '^.+\.tsx?$': [
            'ts-jest',
            {
                useESM: true,
            },
        ],
    },
}

export default jestConfig

Share
Improve this question


Load 4 more related questions


Show fewer related questions

0

Reset to default



Leave a Reply

Your email address will not be published. Required fields are marked *