lundi 1 février 2016

Express mock dependency

Trying to write some tests for my express app. I'm using stripe to process my orders. When I post to /api/order I get the response You cannot use a Stripe token more than once Is there a way to mock out my stripe dependency so that my controller will use the version defined in my test rather than live stripe library?

'use strict';

var should = require('should'),
  request = require('supertest'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  Order = mongoose.model('Order'),
  rewire = require('rewire'),
  sinon = require('sinon');
  var express = require(path.resolve('./config/lib/express'));



/**
 * Globals
 */
var app, agent, credentials, order;

/**
 * Order routes tests
 */
describe('Order CRUD tests', function () {


  before(function (done) {
    // Get application
    app = express.init(mongoose);
    agent = request.agent(app);

    done();
  });


  beforeEach(function (done) {

    this.stripe = {
      charges:{
        create: sinon.stub().yields({"id":"ch_17X2zIJNH141wNRWRkoJI6O3"
                                      ...
                                    })
      },
      tokens:{
        create: sinon.stub().yields({"id":"tok_17GiYeJNH141wNRWrRfSoxKM"
                                      ...
                                    })
      }
    };

    it('should be able to save an order if logged in', function (done) {
        agent.post('/api/auth/signin')
          .send(credentials)
          .expect(200)
          .end(function (signinErr, signinRes) {
                  ...
            }
            // Save a new order
            agent.post('/api/orders')
              .send(order)
              .expect(200)
              .end(function (orderSaveErr, orderSaveRes) {

                // Get a list of orders
                agent.get('/api/orders')
                  .end(function (ordersGetErr, ordersGetRes) {
                    ...

                    (orders[0].title).should.match('Order Title');

                    done();
                  });
              });
          });
      });


  });

Aucun commentaire:

Enregistrer un commentaire