Search code examples
typescriptsinon

why is my typescript import not stubbing with sinon


I am trying to stub an imported method from an external library. I can get this stubbing method to work with internal libraries, where am I going wrong with the external library?

Example:

index.ts
import {format} from "date-fns";

export class Index {
    public now(): string {
        return format(new Date(), "Pp");
    }
}
index.test.ts
import {expect} from 'chai';
import * as sinon from "sinon";
import 'mocha';
import {Index} from './index';

describe("index unit tests", async function () {
    let dfns = await import("date-fns");

    it("get should return mock", async function () {
        sinon.stub(dfns, "format").returns("x");
        expect(new Index().now()).to.equal("x");
    });
});

Solution

  • It is not possible to stub format from date-fns, because format is defined as non-configurable property.

    enter image description here

    (screenshot taken from file: node_modules/date-fns/index.js)

    If you still want it, you can use wrapper method, and then stub the wrapper method.

    For example I create wrapper iFormat to wrap real format at file index.ts.

    // File index.ts
    import { format } from 'date-fns';
    
    export const iFormat = (a: Date, b: string): string => {
      return format(a, b);
    };
    
    export default class Index {
      public now(): string {
        return iFormat(new Date(), 'Pp');
      }
    }
    

    Test file:

    // File: index.test.ts
    import { expect } from 'chai';
    import * as sinon from 'sinon';
    import 'mocha';
    import * as Index from './index';
    
    describe('index unit tests', function () {
        it('get should return mock', function () {
            sinon.stub(Index, 'iFormat').returns('x');
            expect(new Index.default().now()).to.equal('x');
    
        });
    });
    

    When I run it using ts-mocha

    $ npx ts-mocha index.test.ts
    
    
      index unit tests
        ✓ get should return mock
    
    
      1 passing (4ms)