2016-04-22 10 views
0

が私のAccounts.jsモジュールです。下記のmocha test express 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を使用して上記のルートをテストしているし、期待どおりに動作しますから予想されるように、同様にそれは動作しますブラウザフォームの投稿、なぜ私はモカがそれを失敗するのか分からない? この問題を解決するために間違っている部分を軽く投げてください。

大丈夫

+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

上記の2つのテストが間違った方法でデータを送信しているのではないかと疑問に思っています。 –

+0

あまりにも間違っています:P – QoP