【问题标题】:why is my typescript import not stubbing with sinon为什么我的打字稿导入没有与 sinon 存根
【发布时间】:2020-09-30 13:50:35
【问题描述】:

我正在尝试从外部库中存根导入的方法。我可以让这个存根方法与内部库一起使用,我在外部库中哪里出错了?

例子:

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

export class Index {
    public now(): string {
        return format(new Date(), "Pp");
    }
}
索引.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");
    });
});

【问题讨论】:

    标签: typescript sinon


    【解决方案1】:

    无法从 date-fns 存根格式,因为格式被定义为不可配置的属性。

    (截图取自文件:node_modules/date-fns/index.js)

    如果你仍然想要它,你可以使用包装器方法,然后存根包装器方法。

    例如,我创建包装器 iFormat 以在文件 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');
      }
    }
    

    测试文件:

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

    当我使用 ts-mocha 运行它时

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

    【讨论】:

    • 谢谢,我最终做了几乎相同的事情来创建一个包装器
    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 2020-12-15
    • 2016-05-21
    • 1970-01-01
    相关资源
    最近更新 更多