2016-02-11 14 views
7

nie jestem w stanie skrótową konstruktora moment podczas wywoływania go z funkcji format wrócić predefiniowany ciąg, oto przykład Spec, że chciałbym, aby uruchomić z mocha:konstruktor odgałęzienie moment.js z Sinon

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'); 

})); 

jestem w stanie zobaczyć to wyjście używając console.log:

Real call: "1970-01-01T00:00:00.000Z" 
Stub output: 01-06-2025 at 01:00 

Ale wtedy test nie powiedzie się przyczyną 01-06-2025 at 01:00 !== 'FOOBARBAZ' Jak mogę poprawnie szczątkowego, który moment(something).format(...) połączenia?

Odpowiedz

10

Znalazłem odpowiedź na http://dancork.co.uk/2015/12/07/stubbing-moment/

Widocznie chwila naraża swój prototyp używając .fn, więc można:

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

const sandbox = sinon.sandbox.create() 

describe('MyClass',() => { 

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

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

    /* write some tests */ 

}) 
+0

Wygląda na to obejść nie jest już konieczne. Zobacz zmianę [this] (https://github.com/moment/moment/pull/451) –