与Sinon一起使用stub moment.js构造函数

时间:2016-02-11 13:53:55

标签: mocha momentjs sinon chai

使用moment函数调用它时,我无法存根format构造函数以返回预定义的字符串,这是我想用{{1}运行的示例规范}:

mocha

我可以使用it('should stub moment', sinon.test(function() { console.log('Real call:', moment()); const formatForTheStub = 'DD-MM-YYYY [at] HH:mm'; const momentStub = sinon.stub(moment(),'format') .withArgs(formatForTheStub) .returns('FOOBARBAZ'); const dateValueAsString = '2025-06-01T00:00:00Z'; const output = moment(dateValueAsString).format(formatForTheStub); console.log('Stub output:',output); expect(output).to.equal('FOOBARBAZ'); }));

查看此输出
console.log

但是测试失败导致Real call: "1970-01-01T00:00:00.000Z" Stub output: 01-06-2025 at 01:00 如何正确存根01-06-2025 at 01:00 !== 'FOOBARBAZ'来电?

3 个答案:

答案 0 :(得分:18)

我在http://dancork.co.uk/2015/12/07/stubbing-moment/

找到答案

显然,时刻会使用.fn公开其原型,因此您可以:

import { fn as momentProto } from 'moment'
import sinon from 'sinon'
import MyClass from 'my-class'

const sandbox = sinon.createSandbox()

describe('MyClass', () => {

  beforeEach(() => {
    sandbox.stub(momentProto, 'format')
    momentProto.format.withArgs('YYYY').returns(2015)
  })

  afterEach(() => {
    sandbox.restore()
  })

  /* write some tests */

})

答案 1 :(得分:2)

很难从描述中看出来,但是,如果您要在瞬间构造器(而不是lib功能的其余部分)中添加存根,则是因为您正在尝试控制Moment返回的日期(以进行更可靠的测试) ,您可以使用Sinon的usefakeTimer进行此操作。像这样:

// Set up context for mocha test.
      beforeEach(() => {
        this.clock = date => sinon.useFakeTimers(new Date(date));
        this.clock('2019-07-07'); // calling moment() will now return July 7th, 2019.
      });

然后您可以在其他需要在特定日期前后测试逆逻辑的测试中更新日期。

it('changes based on the date', () => {
  this.clock('2019-09-12');
  expect(somethingChanged).to.be.true;
});

答案 2 :(得分:0)

如果所有其他方法都失败,请尝试将其添加到您的测试套件中;

moment.prototype.format = sinon.stub().callsFake(() => 'FOOBARBAZ');