简体   繁体   中英

Unit testing with Mocha and Momentjs

I have a function that I'm trying to unit test with Mocha that uses moment .

function makeRange(timeagoMinutes) {
  var endDate = moment().toISOString();
  var startDate = moment().subtract(timeagoMinutes, 'm').toISOString();
  return startDate + ',' + endDate;
}

Here is what I have so far, but I'm having trouble figuring out what to do with moment . If I call makeRange(40) and run the tests, the string is different each time.

How can I fake the current time (ie moment().toISOString() ?

var rewire = require('rewire');
var controller = rewire('../thecontroller.js');
var moment = require('moment');

describe.only('makeRange', function() {
  var makeRange;

  beforeEach(function() {
    makeRange = controller.__get__('makeRange');
  });

  it('should return a string with a start date and end date', function() {
    //
  });
});

You are using rewire , so you can mock the moment module that's required in the controller to ensure that a known date/time is used:

describe.only('makeRange', function () {

  var makeRange;

  beforeEach(function () {

    var momentMock = function () {
      return moment('2016-08-31T09:00:00Z');
    };
    controller.__set__("moment", momentMock);
    makeRange = controller.__get__("makeRange");
  });

  it('should return a string with a start date and end date', function () {

    expect(makeRange(40)).to.equal('2016-08-31T08:20:00.000Z,2016-08-31T09:00:00.000Z');
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM