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

TPP*_*PPZ 14 mocha.js sinon momentjs chai

在使用moment函数调用它时,我无法存根构造format函数以返回预定义的字符串,这是我想要运行的示例规范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');

}));
Run Code Online (Sandbox Code Playgroud)

我能够看到这个输出使用console.log:

Real call: "1970-01-01T00:00:00.000Z"
Stub output: 01-06-2025 at 01:00
Run Code Online (Sandbox Code Playgroud)

但是测试失败导致01-06-2025 at 01:00 !== 'FOOBARBAZ' 我怎样才能正确存根moment(something).format(...)

Ian*_*nVS 19

我在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 */

})
Run Code Online (Sandbox Code Playgroud)


Lau*_*ren 9

从描述中很难判断,但是如果您尝试存根时刻构造函数(而不是 lib 功能的其余部分)的原因是因为您试图控制时刻返回的日期(为了更可靠的测试),您可以使用 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.
      });
Run Code Online (Sandbox Code Playgroud)

然后,您可以在需要围绕特定日期测试逆逻辑的其他测试的上下文中更新日期。

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