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

Allow to reset the value of MockFunctionContext.#calls #45795

Closed
GauBen opened this issue Dec 9, 2022 · 1 comment
Closed

Allow to reset the value of MockFunctionContext.#calls #45795

GauBen opened this issue Dec 9, 2022 · 1 comment
Labels
feature request Issues that request new features to be added to Node.js.

Comments

@GauBen
Copy link

GauBen commented Dec 9, 2022

What is the problem this feature will solve?

I use globally mocked objects in my tests to allow them to run without an environment:

// Something that looks like a nodemailer object
export const mailer = {
  sendMail: mock.fn(() => Promise.resolve())
};

Because it's global, tests can pollute each other:

it('works', () => {
  mailer.sendMail({ to: "user@example.com" });
  assert.equal(mailer.sendMail.mock.callCount(), 1);
});

it('also works', () => {
  mailer.sendMail({ to: "user@example.com" });
  assert.equal(mailer.sendMail.mock.callCount(), 1); // It fails here, `callCount()` is now 2
});

What is the feature you are proposing to solve the problem?

I want to be able to reset mailer.sendMail.mock.calls:

describe('something', () => {
  beforeEach(() => {
    mailer.sendMail.mock.reset(); // Method name open to bikeshedding
  })
})

get calls() {
return ArrayPrototypeSlice(this.#calls, 0);
}
callCount() {
return this.#calls.length;
}

It could be as simple as:

reset() {
  this.#calls = [];
}

If you're okay with this design, I'm interested in creating a PR with the feature and associated tests.

What alternatives have you considered?

Use another mocking library

Current workaround

I resorted to this hack:

let prevCount = 0;
mailer.sendMail.mock.constructor.prototype.lastCalls = function () {
  const count = this.callCount();
  const tail = this.calls.slice(prevCount);
  prevCount = count;
  return tail;
};
@GauBen GauBen added the feature request Issues that request new features to be added to Node.js. label Dec 9, 2022
@GauBen
Copy link
Author

GauBen commented Dec 9, 2022

Addressed by #45710

@GauBen GauBen closed this as completed Dec 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request Issues that request new features to be added to Node.js.
Projects
None yet
Development

No branches or pull requests

1 participant