Yashua Yashua - 5 months ago 13x
Javascript Question

Mocking Stripe in angular karma tests

I am having issues mocking the Stripe object for Karma tests. It must be the first script loaded (before angular-stripe).

I am loading this in a script in my karma config:

var stripe = new function() {
this.setPublishableKey = function(key) {}

Object.defineProperty(window, 'Stripe', { value: stripe, configurable: true, enumerable: true, writable: true });

This gives
Attempting to configurable attribute of unconfigurable property

I have tried the prototype method but it doesn't recognize any methods I add this way.

window.Stripe = function();
window.Stripe.prototype.setPublishableKey = function() {}

This gives:
undefined is not a constructor (evaluating 'stripeProvider.setPublishableKey(config.stripeId)')
which I believe I have traced to the method not existing (when I dump window.Stripe in angular-stripe it doesnt show the method)

Finally as an object:

window.Stripe = {

Stripe must be available as window.Stripe
. It looks like angular-stripe specifically wants a function.

Whatever Stripe does works if I copy the stripe file locally - I get other errors about not being on stripe.com so I would like to mock it.

Solution Thanks to @estus I was able to solve this the angular way with:

angular.module('angular-stripe', []).provider('stripe', {
setPublishableKey: function() { },
$get: function() {}

The above is enough to override the real loaded
without throwing Stripe missing errors.


angular-stripe is an ultrathin wrapper around Stripe global. One of the main benefits of Angular DI is testability.

Mock angular-stripe units instead of Stripe itself, they are there exactly for this.

module('app', ($provide) => {
  $provide.provider('stripe', function () {
    this.setPublishableKey = jasmine.createSpy();
    this.$get = jasmine.createSpy();