2016-04-22 119 views
0

下面是我的Accounts.js模块。摩卡测试失败表示REST API

var Accounts = function(){ 
    return{ 
     registerNewUser : function(req,res){ 
      console.log(req.body); 
      var email = req.body.email; 
      var password = req.body.password; 

      if(email === undefined || password === undefined){ 
       res.status(400).end('Required Fields Missing'); 
      } 
      else{ 
       email = email.trim(); 
       password = password.trim(); 
       console.log('lengths = ', email.length, ' password length = ', password.length); 
       if(email.length <= 0 || password.length <= 0){ 
        res.status(400).end('Bad Request'); 
       } 
       else{ 
        res.status(200).end('ok'); 
       } 
      } 


     } 
    } 

} 

module.exports = new Accounts(); 

摩卡UnitTests.js

var request = require('supertest'); 
var app = require('../express-app'); 
describe('Testing Route to Register New User', function(){ 
    var server; 
    beforeEach(function(){ 
     server = app.startServer(); 
    }); 
    afterEach(function(done){ 
     server.close(); 
     done(); 
    }); 
    it('Missing required fields test', function(done){ 
     request(app).post('/register',{   
     }).expect(400).end(done); 

    }) ; 
    it('Empty field test',function(done){ 
     request(app).post('/register',{ 
      email:"", 
      password:"   " 
     }).expect(400).end(done);  
    }); 

    it('Should accept the correct email and password',function(done){ 
     request(app).post('/register',{ 
      email:"email", 
      password:"alskdjfs" 
     }).expect(200).end(done);  
    }); 

}); 

摩卡输出:

Testing Route to Register New User 
API Server listening on port 3000 
{} 
    ✓ Missing required fields test 
API Server listening on port 3000 
{} 
    ✓ Empty field test 
API Server listening on port 3000 
{} 
    1) Should accept the correct email and password 


    2 passing (65ms) 
    1 failing 

    1) Testing Route to Register New User Should accept the correct email and password: 
    Error: expected 200 "OK", got 400 "Bad Request" 
     at Test._assertStatus (node_modules/supertest/lib/test.js:232:12) 
     at Test._assertFunction (node_modules/supertest/lib/test.js:247:11) 
     at Test.assert (node_modules/supertest/lib/test.js:148:18) 
     at Server.assert (node_modules/supertest/lib/test.js:127:12) 
     at emitCloseNT (net.js:1521:8) 

我已经使用卷曲CLI测试上述路线和它按预期工作,类似于它的工作原理从预期浏览器表单发帖,我不知道为什么摩卡失败了呢? 有人可以抛出光在我做错了解决这个问题。

Regards

+0

你是否在使用supertest进行请求? – QoP

+0

@QoP是的,我正在使用supertest –

+0

检查我的答案。 – QoP

回答

0

您可能是以错误的方式发送数据。试试这个

it('Should accept the correct email and password',function(done){ 
     var data = { 
      email:"email", 
      password:"alskdjfs" 
     }; 
     request(app).post('/register').send(data).expect(200).end(done);  
    }); 
+0

谢谢冠军,发送数据是问题,想知道以上两个测试是否也是错误的发送数据的方式? –

+0

是的,他们也是错的:P – QoP

相关问题