【问题标题】:Extract superagent request into a method/function?将超级代理请求提取到方法/函数中?
【发布时间】:2014-12-16 12:28:23
【问题描述】:

我是新手,所以请温柔:-)

我有几个单元测试,它们都共享相同的超级代理请求获取和发布。

是否可以提取这些请求以便我可以只运行一个函数而不是复制粘贴整个请求?

例子:

var url = URL_GOES_HERE;

it('responds with totalPrice = 0 when numOfDays = 0', function(done) {
request(url)
    .post('/bookRoom')
    .send({"numOfDays": 0, "checkInDate": todayDate})
    .set('Content-Type', 'application/json')
    .set('Accept', 'application/json')
    .end(function(err, res){
        var body = res.body;
        expect(body.totalPrice).to.eql(0);
        done();
    });

我想将其提取到一个函数中,该函数将接受参数(例如正在发布的 JSON)并且我能够对其进行断言,如示例中所示 - expect(body.totalPrice) .to.eql(0);

【问题讨论】:

    标签: node.js mocha.js superagent


    【解决方案1】:

    当然!将其设置为回调:

    var url = URL_GOES_HERE;
    
    function postBookRoom(postBody, cb) {
        request(url)
            .post('/bookRoom')
            .send(postBody)
            .set(...etc etc...)
            .end(cb); // The callback will be called with parameters err and res
    }
    
    it('responds with totalPrice = 0 when numOfDays = 0', function (done) {
        postBookRoom({
            'numOfDays': 0,
            'checkInDate': todayDate
        }, function (err, res) {
            // This is the function that postBookRoom will call back
            expect(res.body.totalPrice).to.eql(0);
            done();
        });
    });
    

    【讨论】:

    • 哈,这太完美了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 2017-10-22
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多