我正在使用Zombie.js测试我的node.js代码.我有以下api,这是在POST方法: /api/names 并在我的test / person.js文件中跟随代码: it('Test Retreiving Names Via Browser', function(done){ this.timeout(10000); var url =
/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(else部分).我想这是因为在post方法中使用了我的API.
PS:我没有创建任何表单来执行按钮点击查询,因为我正在为移动设备开发后端.
任何有关如何使用POST方法执行API的帮助将不胜感激.
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() }) }) })
对于上面的示例代码,您将需要请求和模块
npm install --save-dev request should