Home > Enterprise >  How to pass optional arguments forward to functions with them
How to pass optional arguments forward to functions with them

Time:01-29

Introduction: I am a junior javascript web-developer and learn more about the unit-testing practice. For that, I use the facebook library jest. The main feature takes form expect(result).matcherFunction(expectation), such that matcherFunction may be, for example, the functionjest.matchers.toBe, available here: https://jestjs.io/docs/expect

Development: The library itself makes it easy to use in the pattern mentioned above. Howver, I wish to apply a studied test pattern which requires function handlers and callback definition, for example, const expectToBe = (result, expectation) => expect(result).toBe(expectation);. The pattern with no expectation value is also easy to apply: const expectToBe = (result) => expect(result).toBeDefined().

Issue application: Matchers with optional arguments, for example, toThrow(error?), toThrowErrorMatchingSnapshot(hint?) or toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot) makes me head scratch since I am not familiar how to pass this optional values forward.

Did I made myself clear? How can we make the problem in an easy form?

CodePudding user response:

Yes, you have made yourself clear. The problem is that you are trying to create a custom function for a Jest matcher that accepts optional arguments, and you are not sure how to pass those optional arguments forward.

One way to make the problem easier is to use the rest operator (...) in your custom function definition to capture any additional arguments passed to the function. For example: const expectToThrow = (result, ...args) => expect(result).toThrow(...args);

This allows you to pass any number of additional arguments to your custom function, which will then be passed on to the Jest matcher.

For example:expectToThrow(() => { throw new Error('error message')}, 'error message')

In this example, the custom function expectToThrow is passed the function that throws the error and a string 'error message' as the argument. The rest operator ...args is used to pass these arguments to the toThrow matcher.

You can also use this same pattern for other matchers that accept optional arguments.

  • Related