Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to mock Task Promise chaining in Jest? #865

Open
ReDrUm opened this issue Nov 29, 2022 · 0 comments
Open

How to mock Task Promise chaining in Jest? #865

ReDrUm opened this issue Nov 29, 2022 · 0 comments

Comments

@ReDrUm
Copy link

ReDrUm commented Nov 29, 2022

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

@ReDrUm ReDrUm changed the title How to mock Task Promise in Jest? How to mock Task Promise chaining in Jest? Nov 29, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant