Allow package to be mocked for testing
See original GitHub issueWe would like to be able to mock out loadStripe
during our unit tests, which run in a restricted, containerized CI/CD environment; however, simply importing loadStripe
has side effects because stripePromise
is created immediately when it’s imported. The TypeScript doc recommends against side-effects in modules, and in this case it makes testing a pain because loadStripe
cannot be mocked out. Plus it’s unexpected: Intuitively, loadStripe
, sounds like a function/action that loads the stripe script, when in fact it’s a wrapper around Promise instance.
Unit testing would be simplified if loadStripe
were a mockable function that loaded the stripe script on demand.
As a side question, using the current version of stripe (1.3.0), what is the proposed way to unit test code that depends on Stripe.js without making HTTP and XHR requests? How can this be mocked out?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:6 (4 by maintainers)
No problem on the late response. This was actually a deal breaker for us so we moved away from using this module.
“[…] by design to enable Stripe’s fraud prevention.” Sure, I understand the reason, but recommending that users either insert a
<script>
tag or callloadStripe()
in top-level code (e.g. in a root module) would make the code testable. The side-effects are, IMHO, overly protective and make dependent code un-testable (or at best, difficult to test).“Is there a reason you cannot mock the entire @stripe/stripe-js module […]?” Yes. Namely because that would involve hooking into the module loading system or something equally duck-punch quail-kick hacky. FWIW we’re using Jasmine, which is the default for Angular.
At a minimum, it would be nice if the documentation provided a suggesting for testing code that depends on Stripe.js without making HTTP/XHR requests, as that may not be possible in a CI/CD-type environment.
As an aside, while I appreciate the libraries and robust documentation that Stripe offers, this integration has been abrasive. There’s no clear path for Angular developers to follow, and as a framework that puts testing in the forefront, this module’s side-effects break the paradigm of injectable, mockable services. In my opinion, that’s a driving reason for using one of the two external Angular libraries for Stripe–ngx-stripe and stripe-angular–or rolling your own (which my team did). Neither of those aforementioned modules uses
@stripe/stripe-js
, by the way; rather, both opt to use the external types,@types/stripe-v3
, and load Stripe manually, which is testable.Hopefully the
pure
entrypoint solved the problem. Please re-open if there are still issues mocking the package.