2016-11-07 15 views
1

我想從量角器測試中調用module.api.create。參照此解決方案: - Chain multiple Node http request我使用的要求,承諾+ CO這樣的: -request-promise + co在量角器測試中的API觸發

//api/module1.js 
var co = require('co'); 
var rp = require('request-promise'); 

exports.create = co(function* def() { 
    var response, token; 
    urlLogin.body.username = username; 
    response = yield rp(urlLogin); 
    //extract token and run other APIs 
    ... 
}).catch(err => console.log); 

而且

//api/api.js 
var module1= require('./module1'), 
exports.module1= function(){ 
    return module1; 
}; 

在我的規格/測試我加入

api = require('../../api/api'); 
api.module1.create; 

問題我面對的是甚至沒有調用「api.module1.create;」行,需求行「api = require('../../ api/api');」被調用自動創建的每次測試執行

+0

呃,你想用'co.wrap'來創建一個函數來代替'co'來評估一個promise嗎? – Bergi

回答

1

coREADME

[email protected]已經發布,現在依賴的承諾。這是走向異步/等待提案的墊腳石。主要的API更改是如何調用co()。之前,co返回了一個「thunk」,然後用回調和可選參數調用。現在,co()返回一個承諾。

我相信你正在尋找co.wrap,它會返回一個函數來執行生成器並返回一個promise(這個函數也可能被稱爲thunk)。只用co急切地執行生成器並返回執行生成器的結果。

const co = require('co') 

co(function*() { 
    // this will run 
    console.log('hello from plain co!') 
}) 

co.wrap(function*() { 
    // this won't run because we never call the returned function 
    console.log('hello from wrapped co 1!') 
}) 

const wrappedfn = co.wrap(function*() { 
    // this runs because we call the returned function 
    console.log('hello from wrapped co 2!') 
}) 

wrappedfn() 

您也可以通過包裝自己的功能,它做同樣的事情爲co.wrap,讓你做更多的東西之後。

exports.create = function() { 
    return co(function*() { 
    // this will run only when exports.create is called 
    console.log('hello from plain co!') 
    }) 
    // If you want to do stuff after and outside the generator but inside the enclosing function 
    .then(...) 
}