所以我遇到了另一个障碍,我正在与...我有一个方法是一个同步调用,并在此它调用promise,async,方法。TDD:Sinon 2.x并试图测试使用异步的同步方法
在我的应用程序我有以下几点:
export class App {
constructor(menuService) {
_menuService = menuService;
this.message = "init";
}
configureRouter(config, router) {
console.log('calling configureRouter');
_menuService.getById(1).then(menuItem => {
console.log('within then');
console.log(`configureRouter ${JSON.stringify(menuItem, null, 2)}`);
const collection = menuItem.links.map(convertToRouteCollection);
console.log(`collection ${JSON.stringify(collection, null, 2)}`);
//I think there is an issue with asyn to synch for the test
config.map(collection);
}).catch(err => {
console.error(err);
});
console.log('calling configureRouter assign router');
this.router = router;
}
}
测试我试过摩卡内的下列
...
it('should update router config', function() {
const expectedData = {
name: "main menu",
links: [{
url: '/one/two',
name: 'link name',
title: 'link title'
}]
};
const configMapStub = sinon.stub();
const config = {
map: configMapStub
};
const routerMock = sinon.stub();
let app = null;
const actualRouter = null;
let menuService = null;
setTimeout(() => {
menuService = {
getById: sinon.stub().returns(Promise.resolve(expectedData).delay(1))
};
app = new App(menuService);
app.configureRouter(config, routerMock);
}, 10);
clock.tick(30);
expect(app.router).to.equal(routerMock);
expect(menuService.getById.calledWith(1)).to.equal(true);
//console.log(configMapStub.args);
expect(configMapStub.called).to.equal(true);
const linkItem = expectedData.links[0];
const actual = [{
route: ['', 'welcome'],
name: linkItem.name,
moduleId: linkItem.name,
nav: true,
title: linkItem.title
}];
console.log(`actual ${JSON.stringify(actual, null, 2)}`);
expect(config.map.calledWith(actual)).to.equal(true);
});
...
不管是什么,我得到configMockStub总是得到错误的,而我我得到的menuService.getById.calledWith(1).to.equal(true)等于true。 上面的测试是试图让'时间'通过。我已经尝试过,没有同样的失败。 我真的很关注如何测试这个想法。也许我的代码在这个方法中引用了一个promise。
我可以说的唯一的事情是,我没有任何关于configureRouter方法的选择。任何指导表示赞赏。
谢谢! 凯利
一般来说,主要问题是'configureRouter'应该是正确的异步,否则唯一能够测试它的方法是用黑客。 – robertklep