Thursday, 11 May 2017

Unexpected Sinon.js behaviour

I'm trying to stub the Stripe module for unit testing using Mocha and Sinon.js.

I require Stripe like this :

const stripe = require('stripe');
const stubbedStripeClient = stripe.Stripe('test');

At the root of my tests (inside my top-level describe()) I have this :

before('stub root', () => {
  sinon.stub(stripe, 'Stripe').returns(stubbedStripeClient);
});

Then, in the describe() block where I actually would call a Stripe method, I have this before() hook :

let stub;
before('stub', () => {
  console.log(typeof stubbedStripeClient.customers.create);
  stub = sinon.stub(stubbedStripeClient.customers, 'create', ({id: 'a-stripe-customer-id'}));
});

This is where I don't understand what happens. The first line in the hook (console.log) outputs:

function

The second line throws this exception :

TypeError: Attempted to wrap undefined property create as function

How is this possible? How can it be a function on one line and be undefined on the very next line?

I looked at the Sinon.js source, and this check is performed here. If I then look at their isFunction function, it performs the same check I have in my console.log. I'm puzzled.



via Samuel Bolduc

No comments:

Post a Comment