[英]TDD: Sinon 2.x and trying to test a sync method that uses async
所以我遇到了另一個難題,我正在與之抗爭……我有一個方法是一個同步調用,在這個方法中它調用了一個promise,async,方法。
在我的應用程序中,我有以下內容:
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);
});
...
無論如何,當我將menuService.getById.callWith(1).to.equal(true)設置為true時,configMockStub始終會為false。 上面的測試是嘗試讓“時間”通過的嘗試。 我已經嘗試過,但同樣失敗了。 我真的很想出如何測試的想法。 也許我在此方法中引用一個Promise的代碼錯誤。
我只能說我對configureRouter方法沒有任何選擇。 任何指導表示贊賞。
謝謝! 凱莉
簡短答案:
我最近發現我試圖使configureRouter方法成為同步調用(使其使用async await關鍵字)。 我發現Aurelia確實允許使用該方法。 因此,該測試不再是問題。
更長的答案:
另一部分是,我遇到了很多通貨膨脹問題,包括摩卡游樂和wallaby.js游樂。 由於某種原因,這兩個人的表現不佳。
在上面的測試中,另一件事是還要更改以下內容:
it('should update router config', function () {
至
it('should update router config', async function () {
我覺得還有一步,但是現在我不記得了。 無論哪種情況,知道我都可以兌現諾言使奧雷利亞變得更加輕松。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.