dimanche 26 juillet 2015

Using Angular's di.js, how can I record the result of spies passed to the injector?

Angular's dependency injection framework allows mock objects to be injected for testing purposes. The injector automatically instantiates objects passed to it before injecting them, so how can I record the internal workings of my code using a spy?

For example, in the below test I pass a MockTransactionModel into my system under test. I then wish to assert that the description field is equal to the same field in the request body (which I've mocked out), however, because the DI framework is creating an instance of the MockTransactionModel before injecting it, I have no reference to the actual object passed to sut.

describe('adding transaction', function() {
  var sut;

  beforeEach(function() {
    var injector = new di.Injector([MockTransactionModel]);
    sut = injector.get(TransactionController);
  })

  it('should save the description from the request body', function() {
    sut.add(mockRequest, null);

    expect(MockTransactionModel().description).toBe(mockRequest.body.description);
  });
});

In a sentence I suppose my question is: how can I can reference objects instantiated by the DI framework? I'm aware that I could simply inject my dependencies manually but I feel that somewhat negates introducing a DI framework.

MockTransactionModel

module.exports = MockTransactionModel;

var TransactionModel = require('../../app/models/transaction.model');
var di = require('di');

di.annotate(MockTransactionModel, new di.Provide(TransactionModel));

function MockTransactionModel() {
  return {
    description: '',
    amount: 0
  }
}

TransactionController (SUT)

module.exports = TransactionController;

var di = require('di');
var TransactionModel = require('../models/transaction.model');

di.annotate(TransactionController, new di.Inject(TransactionModel));

function TransactionController(transactionModel) {

  this.add = function(req, res) {
    transactionModel.description = req.body.description;
    transactionModel.amount = req.body.amount;
  };
}

Aucun commentaire:

Enregistrer un commentaire