【问题标题】:How can I correctly specify both types for a mock with ts-sinon?如何正确指定使用 ts-sinon 的模拟的两种类型?
【发布时间】:2022-01-05 21:10:10
【问题描述】:

有没有办法在 ts-sinon 存根构造函数上声明类型,以便打字稿理解来自 ts-sinon 和模拟类的属性和方法都可用?

下面的代码有效,但我希望foo 上的类型比any 更具体:

import { expect } from 'chai';
import * as sinon from 'ts-sinon'

class Foo {
  public getFoo(): string {
    return 'foo';
  }
}

describe('Foo', () => {
  it('can mock methods on Foo', () => {
    // How can I specify a specific type that will allow properties
    // and methods from both Foo and the stubConstructor return? 
    let foo: any = sinon.stubConstructor(Foo);
    foo.getFoo.returns('bar');
    expect(foo.getFoo()).to.equal('bar');
  });
});

我尝试了诸如 Foo | sinon.StubbedInstance<Foo> 之类的类型,但找不到合适的类型。

【问题讨论】:

    标签: typescript sinon


    【解决方案1】:

    显然只有sinon.StubbedInstance<Foo> 包括这两个集合。在发布问题后,我终于让它工作了。

    import { expect } from 'chai';
    import * as sinon from 'ts-sinon'
    
    class Foo {
      public getFoo(): string {
        return 'foo';
      }
    }
    
    describe('Foo', () => {
      it('can mock methods on Foo', () => {
        let foo: sinon.StubbedInstance<Foo> = sinon.stubConstructor(Foo);
        foo.getFoo.returns('bar');
        expect(foo.getFoo()).to.equal('bar');
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-10-27
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 2014-09-15
      • 2021-05-26
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      相关资源
      最近更新 更多