如果我将 sinon 与 typescript 一起使用,那么如何将 sinon 模拟转换为我的对象的实例?
例如,将返回一个SinonMock,但我的被测控制器可能需要将特定服务传递给其构造函数。
var myServiceMock: MyStuff.MyService = <MyStuff.MyService (sinon.mock(MyStuff.MyService));
controllerUnderTest = new MyStuff.MyController(myServiceMock, $log);
sinon 可以与 Typescript 一起使用吗?
Sinon 可以很容易地基于构造函数创建一个存根,如果,而不是mock
,你使用createStubInstance
method.
一个使用的例子mocha https://github.com/mochajs/mocha, chai http://chaijs.com/, sinon http://sinonjs.org/ and 兴农柴 https://github.com/domenic/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;
});
});
I've 发表了一篇文章 https://janmolak.com/mocking-javascript-a-little-26efb5f7f52a#.ulfyw64hq,如果您想了解有关不同测试替身以及如何将它们与 Sinon.js 一起使用的更多信息,您可能会发现它很有用。
希望这可以帮助!
Jan
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)