【问题标题】:Calling API with POST method via Zombie.js browser通过 Zombie.js 浏览器使用 POST 方法调用 API
【发布时间】:2013-05-24 06:43:47
【问题描述】:

我正在使用 Zombie.js 测试我的 node.js 代码。我有以下 api,它在 POST 方法中:

/api/names

以及我的 test/person.js 文件中的以下代码:

it('Test Retreiving Names Via Browser', function(done){
    this.timeout(10000);
    var url = host + "/api/names";
    var browser = new zombie.Browser();
    browser.visit(url, function(err, _browser, status){
       if(browser.error)
       {
           console.log("Invalid url!!! " + url);
       }
       else
       {
           console.log("Valid url!!!" + ". Status " + status);
       }
       done();
    });
});

现在,当我从终端执行命令 mocha 时,它会进入 browser.error 状态。但是,如果我将我的 API 设置为 get 方法,它会按预期工作并进入 Valid Url (其他部分)。我想这是因为我的 API 在 post 方法中。

PS:当我正在为移动设备开发后端时,我没有创建任何表单来执行单击按钮时的查询。

任何有关如何使用 POST 方法执行 API 的帮助将不胜感激。

【问题讨论】:

    标签: node.js testing post browser zombie.js


    【解决方案1】:

    Zombie 更多地用于与实际网页交互,并且在发布请求的情况下是实际表单。

    对于您的测试,请使用 request 模块并自己手动制作发布请求

    var request = require('request')
    var should = require('should')
    describe('URL names', function () {
      it('Should give error on invalid url', function(done) {
        // assume the following url is invalid
        var url = 'http://localhost:5000/api/names'
        var opts = {
          url: url,
          method: 'post'
        }
        request(opts, function (err, res, body) {
          // you will need to customize the assertions below based on your server
    
          // if server returns an actual error
          should.exist(err)
          // maybe you want to check the status code
          res.statusCode.should.eql(404, 'wrong status code returned from server')
          done()
        })
      })
    
      it('Should not give error on valid url', function(done) {
        // assume the following url is valid
        var url = 'http://localhost:5000/api/foo'
        var opts = {
          url: url,
          method: 'post'
        }
        request(opts, function (err, res, body) {
          // you will need to customize the assertions below based on your server
    
          // if server returns an actual error
          should.not.exist(err)
          // maybe you want to check the status code
          res.statusCode.should.eql(200, 'wrong status code returned from server')
          done()
        })
      })
    })
    

    对于上面的示例代码,您将需要 requestshould 模块

    npm install --save-dev request should
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-03
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 2016-10-19
      • 2017-11-27
      • 1970-01-01
      相关资源
      最近更新 更多