Home > Enterprise >  Mock function based on interface with jest-ts
Mock function based on interface with jest-ts

Time:11-08

I'm trying to find the best way to test Azure Functions written in TypeScript using Jest. This requires passing a Context object into with a log property that satisfies the following interface:

   interface Logger {
        (...args: any[]): void;
        error(...args: any[]): void;
        warn(...args: any[]): void;
        info(...args: any[]): void;
        verbose(...args: any[]): void;
    }

I don't care about testing the calls to any of these methods, I merely care about passing a valid function into the object. I'm looking for the quickest way to create a mock function to allow any of the methods in the interface to be called, without having to explicitly define my own Logger implementation for testing purposes.

I was hoping to get it to work with jest-mock-extended's mockDeep<T> function but couldn't get it to work. I'd rather avoid pulling in dedicated packages like Moq.ts. Is there a simple way to create a mock function based on this interface with (ts-)jest's built-in tools?

CodePudding user response:

I suppose you already have implemented Logger in your application. You can use jest's jest.createMockFromModule(moduleName) to generate auto-mock of your implementation

here's an example

  • Related