unit-testing - 我如何将 Sinon 与 Typescript 一起使用?

标签 unit-testing typescript sinon

如果我将 sinon 与 typescript 一起使用,那么我该如何将 sinon mock 转换为我的对象实例?

例如,将返回一个 SinonMock,但我的被测 Controller 可能需要将特定服务传递给其构造函数。

var myServiceMock: MyStuff.MyService = <MyStuff.MyService (sinon.mock(MyStuff.MyService));

controllerUnderTest = new MyStuff.MyController(myServiceMock, $log);

sinon 可以和 Typescript 一起使用吗?

最佳答案

如果您不使用 mock,而是使用 createStubInstance 方法,Sinon 可以很容易地创建基于构造函数的 stub 。

使用 mocha 的示例, chai , sinonsinon-chai ,可能看起来像这样:

import * as sinon from 'sinon';
import * as chai from 'chai';

// ... imports for the classes under test

const expect    = chai.expect;
const sinonChai = require("sinon-chai");

chai.use(sinonChai);

describe('MyController', () => {
    it('uses MyService', () => {

        let myService  = sinon.createStubInstance(MyStuff.MyService),
            controller = new MyStuff.MyController(myService as any, ...);

        // ... perform an action on the controller 
        // that calls myService.aMethodWeAreInterestedIn

        // verify if the method you're interested in has been called if you want to
        expect(myService.aMethodWeAreInterestedIn).to.have.been.called;
    });
});

我已经 published an article ,如果您想详细了解不同的测试替身以及如何将它们与 Sinon.js 一起使用,您可能会发现它很有用。

希望这对您有所帮助!

一月

关于unit-testing - 我如何将 Sinon 与 Typescript 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28156057/

相关文章:

c++ - 使用googlemock模拟正在测试的函数的内部调用

python - 当 python 模拟同时具有返回值和副作用列表时会发生什么?

javascript - TypeScript如何在数组的Reduce函数中设置累积值和初始值的类型

node.js - 使用 eval 处理 typescript 类型

javascript - 正确测试 backbone.js 中的路由器?

javascript - 使用异步 ajax 调用的 Sinon/Mocha 测试没有返回 promise

javascript - 模拟本地存储,用于测试两种方法的功能/覆盖

unit-testing - Flutter: 'package:shared_preferences/shared_preferences.dart':断言失败:第 33 行 pos 16: 'key.startsWith(_prefix)':不正确

android - 无法让 JUnit 测试在 Android Studio 中失败

javascript - typescript 中可能具有未定义值的逻辑运算符