DarkLite1
DarkLite1

Reputation: 14705

How to check if a function was called with jest

I would like to test if a new Apollo server object is created when calling the function getApolloServer() below:

// src/apolloServer.ts
import { ApolloServer } from 'apollo-server'
import { buildSchema } from 'type-graphql'
import { HelloWorldResolver } from './resolvers/HelloWorldResolver'
import { MovieResolver } from './resolvers/MovieResolver'

export const getApolloServer = async () => {
  return new ApolloServer({
    schema: await buildSchema({
      resolvers: [HelloWorldResolver, MovieResolver],
    }),
    context: ({ req, res }) => ({ req, res }),
  })
}

My jest test code looks like this:

// src/apolloServer.test.ts
import { ApolloServer } from 'apollo-server'
import { getApolloServer } from './apolloServer'

jest.mock('apollo-server')

describe('Apollo server', () => {
  it('should create a new Apollo server', () => {
    getApolloServer()
    expect(ApolloServer).toBeCalledTimes(1)
  })
})

Jest reports Received number of calls: 0 instead of the expected 1. I'm new to testing and javascript so I'm probably missing something obvious here but I couldn't find a proper example in the docs on how to do this.

Thank you for your help.

Upvotes: 0

Views: 190

Answers (1)

alchemist95
alchemist95

Reputation: 794

Your function is an async function and so should your test be. Make your unit test async and await on getApolloServer(). Check what is the result of await getApolloServer(). That should be an instance of ApolloServer.

https://jestjs.io/docs/en/expect#tobeinstanceofclass

Upvotes: 1

Related Questions