Search code examples
typescriptjestjsts-jest

Typescript Error TS(2304) jest.MockedFunction - What Is The Correct Usage For jest.MockedFunction?


Can anybody help resolve a Typescript error that I am receiving in the following code listed below.

The line of code that raises the error is const mockedFunction = createRepo as jest.MockedFunction<typeof create_publish_repository>;

I am trying to learn how to use jest.MockedFunction. The error that I receive in VSCode is:

  • Cannot find name createRepo. ts(2304) any
import { PublishRepository, create_publish_repository } from "../../../../repository";
jest.mock("../../../../repository");

describe("/api/publish/[id]", () => {
  test("returns a post with published state set to true", async () => {
      // this raises an error
      const mockedFunction = createRepo as jest.MockedFunction<typeof create_publish_repository>;
  }

Repository ./publish.repo

import { Post } from "@prisma/client"
import { Context } from "../context"


export class PublishRepository {
    private context: Context

    constructor(context: Context) {
        this.context = context
    }

    async set_published(post_id: string | string[]): Promise<Post> {
        return await this.context.prisma.post.update({
            where: { id: Number(post_id) },
            data: { published: true },
        });
    }
}


export const create_publish_repository = (context: Context): PublishRepository => {
    return new PublishRepository(context)
}

Repository Module ./index.ts

export { create_publish_repository, PublishRepository } from "./publish.repo";

Solution

  • Solved it...I needed to rename my mocked function variable to match the name of the imported function intended for mocking.

    Since there is no function imported called createRepo, typescript raises the error.

    No import called createRepo, raises error

    import { PublishRepository, create_publish_repository } from "../../../../repository";
    
    const mockedFunction = createRepo as jest.MockedFunction<typeof create_publish_repository>;
    

    Corrected mocked function name create_publish_repository to match import

    import { PublishRepository, create_publish_repository } from "../../../../repository";
    
    const mockedFunction = create_publish_repository as jest.MockedFunction<typeof create_publish_repository>;