如果我将 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 , sinon和 sinon-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/