Skip to content

How to mock Task Promise chaining in Jest? #865

Open
@ReDrUm

Description

@ReDrUm

Hi,

I'm familiar with how to mock simple-git using jest.mock which works fine for single method calls. But if an implementation is using chaining via the Task Promises API, then the mocking becomes much more challenging.

For example the docs show you can do await git.init().addRemote('origin', '...remote.git');

Which under the hood is achieved because each API method (such as init and addRemote) internally invokes this._runTask which looks like the below:

protected _runTask<T>(task: SimpleGitTask<T>, then?: SimpleGitTaskCallback<T>) {
      const chain = this._executor.chain();
      const promise = chain.push(task);

      if (then) {
         taskCallback(task, promise, then);
      }

      return Object.create(this, {
         then: { value: promise.then.bind(promise) },
         catch: { value: promise.catch.bind(promise) },
         _executor: { value: chain },
      });
   }

Do you have an example of how one might mock simple-git to support for the same chaining? e.g.

class MockedSimpleGit {
    constructor() { }
    async init() {
        return ...?
    }
    async addRemote() {
        return ...?
    }
}

jest.mock('simple-git', () => ({
    __esModule: true,
    ...jest.requireActual('simple-git'),
    default: jest.fn().mockImplementation(() => new MockedSimpleGit())
}));

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions