mardi 9 février 2021

Stub functions before launching app from child process

I want to create a test environment that I can run to then test some features of my app manually. In this test environment I want to stub some methods, like api calls to stripe -my payment processor. But I'm having trouble stubbing methods before launching the app. When I launch a file using child_process, stubbing isn't working.

app.js:

const stripeInterface = require('./stripeInterface');

stripeInterface.charge();

stripeInterface.js:

const stripe = {
  charge: () => console.log('making an http request to Stripe. This may take a while...'),
};
module.exports = stripe;

testenv.js
Here I try to stub the Stripe interface and then launch app.js:

const { exec } = require('child_process');
const sinon = require('sinon');
const stripe = require('./stripeInterface');

sinon.stub(stripe, 'charge').callsFake(() => console.log('skipping call to stripe'));
exec('node app.js', (error, stdout, stderr) => {
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
  if (error !== null) {
    console.log(`exec error: ${error}`);
  }
});

When I run testenv.js I get in the console:

making an http request to Stripe. This may take a while...

But I would expect the stub to replace it and give me skipping call to stripe.

Aucun commentaire:

Enregistrer un commentaire