如何存根打字稿接口/类型定义?

How to stub a Typescript-Interface / Type-definition?

我在 AngularJS 1.X 项目中使用 Typescript。我出于不同的目的使用不同的 Javascript 库。为了对我的源代码进行单元测试,我想使用 Typings(= 接口)存根一些依赖项。我不想使用 ANY 类型,也不想为每个接口方法编写一个空方法。

我正在寻找一种方法来做类似的事情:

let dependency = stub(IDependency);
stub(dependency.b(), () => {console.log("Hello World")});
dependency.a(); // --> Compile, do nothing, no exception
dependency.b(); // --> Compile, print "Hello World", no exception

我现在的痛苦是,我要么使用 any 并实现在我的测试用例中调用的所有方法,要么我实现接口并实现完整的接口。那些无用的代码太多了:(.

如何生成一个对象,该对象对每个方法都有一个空的实现并且是类型化的?我将 Sinon 用于模拟目的,但我也愿意使用其他库。

PS:我知道 Typescript 会擦除接口...但我仍然想解决这个问题:)。

很少有库允许这样做 TypeMoqTeddyMocksTypescript-mockify 可能是比较流行的库之一。

检查 github 存储库并选择您更喜欢的一个: 链接:

您也可以使用更流行的库,例如 Sinon,但首先您必须使用 <any> 类型,然后将其缩小为 <IDependency> 类型 ()

我一直在使用 qUnit 和 Sinon 编写 Typescript 测试,我也经历过与您描述的完全相同的痛苦。

让我们假设您依赖于如下接口:

interface IDependency {
    a(): void;
    b(): boolean;
}

通过使用基于 sinon stubs/spies 和转换的几种方法,我设法避免了额外 tools/libraries 的需要。

  • 使用空对象字面量,然后直接将sinon stubs赋值给代码中使用的函数:

    //Create empty literal as your IDependency (usually in the common "setup" method of the test file)
    let anotherDependencyStub = <IDependency>{};
    
    //Set stubs for every method used in your code 
    anotherDependencyStub.a = sandbox.stub(); //If not used, you won't need to define it here
    anotherDependencyStub.b = sandbox.stub().returns(true); //Specific behavior for the test
    
    //Exercise code and verify expectations
    dependencyStub.a();
    ok(anotherDependencyStub.b());
    sinon.assert.calledOnce(<SinonStub>anotherDependencyStub.b);
    
  • 将对象字面量与代码所需方法的空实现一起使用,然后根据需要在 sinon spies/stubs 中包装方法

    //Create dummy interface implementation with only the methods used in your code (usually in the common "setup" method of the test file)
    let dependencyStub = <IDependency>{
        a: () => { }, //If not used, you won't need to define it here
        b: () => { return false; }
    };
    
    //Set spies/stubs
    let bStub = sandbox.stub(dependencyStub, "b").returns(true);
    
    //Exercise code and verify expectations
    dependencyStub.a();
    ok(dependencyStub.b());
    sinon.assert.calledOnce(bStub);
    

当你将它们与 sinon 沙箱和常见的 setup/teardown 结合使用时,它们工作得很好,就像 qUnit 模块提供的那样。

  • 在常见设置中,您为依赖项创建一个新的沙箱和模拟对象文字。
  • 在测试中您只需指定 spies/stubs。

类似这样的事情(使用第一个选项,但如果您使用第二个选项,将以相同的方式工作):

QUnit["module"]("fooModule", {
    setup: () => {
        sandbox = sinon.sandbox.create();
        dependencyMock = <IDependency>{};
    },
    teardown: () => {
        sandbox.restore();
    }
});

test("My foo test", () => {
    dependencyMock.b = sandbox.stub().returns(true);

    var myCodeUnderTest = new Bar(dependencyMock);
    var result = myCodeUnderTest.doSomething();

    equal(result, 42, "Bar.doSomething returns 42 when IDependency.b returns true");
});

我同意这仍然不是理想的解决方案,但它工作得相当好,不需要额外的库并将所需的额外代码量保持在较低的可管理水平。

我认为简短的回答是,这在 Typescript 中是不可能的,因为该语言不提供编译时或 运行-time "reflection" .模拟库不可能迭代接口的成员。

查看主题:https://github.com/Microsoft/TypeScript/issues/1549

这对 TDD 开发人员来说是不幸的,因为模拟依赖项是开发工作流程的核心部分。

但是,如其他答案所述,有许多技术可用于快速对方法进行存根。这些选项可能会完成这项工作,只需稍作心理调整。

编辑:Typescript 抽象语法树 AST 是编译时 "introspection" - 可能用于生成模拟。不过不知道有没有人做过实用的库

现在有可能了。我发布了增强版的 typescript 编译器,使接口元数据在运行时可用。例如,你可以这样写:

interface Something {

}

interface SomethingElse {
    id: number;
}

interface MyService {
    simpleMethod(): void;
    doSomething(p1: number): string;
    doSomethingElse<T extends SomethingElse>(p1: Something): T;
}

function printMethods(interf: Interface) {
    let fields = interf.members.filter(m => m.type.kind === 'function'); //exclude methods.
    for(let field of fields) {
        let method = <FunctionType>field.type;
        console.log(`Method name: ${method.name}`);
        for(let signature of method.signatures) {
            //you can go really deeper here, see the api: reflection.d.ts
            console.log(`\tSignature parameters: ${signature.parameters.length} - return type kind: ${signature.returns.kind}`);
            if(signature.typeParameters) {
                for(let typeParam of signature.typeParameters) {
                    console.log(`\tSignature type param: ${typeParam.name}`); //you can get constraints with typeParam.constraints
                }
            }
            console.log('\t-----')
        }
    }
}

printMethods(MyService); //now can be used as a literal!!

这是输出:

$ node main.js
Method name: simpleMethod
        Signature parameters: 0 - return type kind: void
        -----
Method name: doSomething
        Signature parameters: 1 - return type kind: string
        -----
Method name: doSomethingElse
        Signature parameters: 1 - return type kind: parameter
        Signature type param: T
        -----

利用所有这些信息,您可以根据需要以编程方式构建存根。

你可以找到我的项目here

最新TypeMoq(ver 1.0.2)支持模拟TypeScript接口,只要运行时(nodejs/browser)支持ES6引入的Proxy全局对象即可。

所以,假设 IDependency 看起来像这样:

interface IDependency {
    a(): number;
    b(): string;
}

然后用 TypeMoq 模拟它就这么简单:

import * as TypeMoq from "typemoq";
...
let mock = TypeMoq.Mock.ofType<IDependency>();

mock.setup(x => x.b()).returns(() => "Hello World");

expect(mock.object.a()).to.eq(undefined);
expect(mock.object.b()).to.eq("Hello World");

您可以尝试moq.ts,但这取决于代理对象

interface IDependency {
  a(): number;
  b(): string;
}


import {Mock, It, Times} from 'moq.ts';

const mock = new Mock<IDependency>()
  .setup(instance => instance.a())
  .returns(1);

mock.object().a(); //returns 1

mock.verify(instance => instance.a());//pass
mock.verify(instance => instance.b());//fail

SafeMock 非常好,但遗憾的是它现在似乎没有维护。 完全公开,我曾经和作者一起工作过。

import SafeMock, {verify} from "safe-mock";

const mock = SafeMock.build<SomeService>();

// specify return values only when mocks are called with certain arguments like this
when(mock.someMethod(123, "some arg")).return("expectedReturn");

// specify thrown exceptions only when mocks are called with certain arguments like this
when(mock.someMethod(123, "some arg")).throw(new Error("BRR! Its cold!")); 

// specify that the mock returns rejected promises with a rejected value with reject
when(mock.someMethod(123)).reject(new Error("BRR! Its cold!"));

//use verify.calledWith to check the exact arguments to a mocked method
verify(mock.someMethod).calledWith(123, "someArg");

SafeMock 不会让您 return 从模拟中输入错误的类型。

interface SomeService {
    createSomething(): string;
}

const mock: Mock<SomeService> = SafeMock.build<SomeService>();

//Won't compile createSomething returns a string
when(mock.createSomething()).return(123); 

来自 npmjs:

Mocking interfaces
You can mock interfaces too, just instead of passing type to mock function, set mock function generic type Mocking interfaces requires Proxy implementation

let mockedFoo:Foo = mock<FooInterface>(); // instead of mock(FooInterface)
const foo: SampleGeneric<FooInterface> = instance(mockedFoo);

ts-mockito 从 2.4.0 版本开始支持模拟接口: