Skip to content

How to mock a standalone function? #36

@mebble

Description

@mebble

I want to mock a standalone function (i.e. a function that's not a method of some object) but I can't find information on that in the readme.

Here is a simplified version of what I'm trying to do:

type Callback = (x: number) => void;

const caller = (callback: Callback) => {
    callback(Math.random())
}

let mockCallback: Callback = mock<Callback>();

caller(mockCallback);            // fails when using mock without instance
caller(instance(mockCallback));  // fails when using mock with instance
caller(x => console.log(x))      // works when not using a mock

As shown above, the first two caller(...) calls that use the mock would fail. They fail with the error:

TypeError: callback is not a function
 ❯ caller src/test.test.ts:7:5
      5|
      6| const caller = (callback: Callback) => {
      7|     callback(Math.random())
       |     ^
      8| }

I want to mock a standalone function so that I can capture its arguments and do stuff with them. Could you please help me out? Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions