2

Code :

Model = {};

var functionToTest = function (dataPoints) {
    return Model.getDataPointValue(dataPoints, function (dataPoint) {
        if (dataPoint.unit === 'unit') {
            return dataPoint.value;
        }
    });
};
Model.functionToTest = functionToTest;

Test Case :

  describe ('functionToTest', function () {
    it ('validates correct value is returned', function () {
      var dataPoints = [{
        'unit': 'unit',
        'value' : 1
      }];

      var mock = sinon.mock(Model);
      mock.expects('getDataPointValue').once().withExactArgs(dataPoints, function (dataPoint) {
        if (dataPoint.unit === 'unit') {
          return dataPoint.value;
        }
      });

      Model.functionToTest(dataPoints);

      mock.verify();
    });
  });

Response :

ExpectationError: Unexpected call: getDataPointValue([{ unit: "unit", value: 1 }], function () {})
    Expected getDataPointValue([{ unit: "unit", value: 1 }], function () {}) once (never called)

I cant figure out why it wouldnt accept the same function definition as a parameter. Any clues ? Is there a different way to test function parameters being functions in mocha using sinon ?

shek
  • 12,721
  • 2
  • 26
  • 23

1 Answers1

2

If you are always passing the same function to the getDataPointValue, there's no need to test if that function was passed, you can test only if the first argument was passed like this:

mock.expects('getDataPointValue').once().withArgs(dataPoints);
thitemple
  • 5,833
  • 4
  • 42
  • 67
  • Yup, but thats a partial solution since the code that is in the function being passed in is never checked for. – Shriniket Sarkar Apr 06 '16 at 15:49
  • 1
    It tests that the getDataPoint is called with the correct arguments. If you want to test that anonymous function you should refactor it into a named function and create another test for that. – thitemple Apr 06 '16 at 23:23