2016-10-08 48 views
0

我正在爲一個簡單的NodeJS應用程序編寫單元測試,並且出於某種原因,我無法檢索響應正文。它會得到正確的響應代碼(對於成功的請求或者是200,對於無效的請求是422),但是主體看起來是空的。此外,當我與http12完全相同的請求,它的作品就像魅力。日誌記錄還顯示控制器按預期工作。node-fetch收到空體

歡迎任何想法或建議。

這裏的控制器部分:

function register (req, res) { 
    return _findUser({email: req.body.email}) 
    .then(user => { 
     if (user) { 
     console.log('EMAIL TAKEN'); 
     return Promise.reject({message: 'This email is already taken'}); 
     } 

     let params = _filterParams(req.body); 
     if (_isRegistrationValid(params)) { 
     console.log('REGISTRATION VALID'); 
     return params; 
     } else { 
     console.log('PARAMS INVALID'); 
     return Promise.reject({message: 'Params invalid'}); 
     } 
    }) 
    .then(_createUser) 
    .then(_generateToken) 
    .then(token => { 
     console.log('SENDING TOKEN'); 
     console.log(token); 
     res.send({token: token}); 
    }) 
    .catch(error => { 
     console.log('CATCH ERROR'); 
     res.status(422).send(error); 
    }); 
} 

這裏的測試部分:

it ('Returns token when data is valid', done => { 
    fetch(`http://localhost:${testPort}/api/register`, { 
    headers: {'Content-Type': 'application/json'}, 
    method: 'POST', 
    body: JSON.stringify({email: '[email protected]', password: 'password', confirmPassword: 'password'}) 
    }) 
    .then(response => { 
     assert(response.ok); // this part works ok 
     expect(response.body.token).to.exist; // this part fails 
     done(); 
    }) 
    .catch(done); 
}); 

這裏的httpie輸出:

kpr$ http post localhost:4000/api/register email="[email protected]" password="password" confirmPassword="password" 
HTTP/1.1 200 OK 
Connection: keep-alive 
Content-Length: 941 
Content-Type: application/json; charset=utf-8 
Date: Sat, 08 Oct 2016 11:39:30 GMT 
ETag: W/"3ad-uBdW+HLbY7L2gb65Y+zptQ" 
X-Powered-By: Express 

{ 
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9_long_token_string_2M" 
} 

下面是測試輸出:

REGISTRATION VALID 
_createUser 
(node:70495) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html 
_generateToken 
SENDING TOKEN 
eyJhbGciOiJIU_long_token_string_lmYA 

    0 passing (160ms) 
    2 pending 
    1 failing 

    1) Authorization Registration Returns token when data is valid: 
    AssertionError: expected undefined to exist 
     at fetch.then.response (test/auth-controller-spec.js:57:41) 
     at process._tickCallback (internal/process/next_tick.js:103:7) 

打印出響應的身體從內取()顯示了一些巨大的對象:

PassThrough { 
    _readableState: 
    ReadableState {etc...} 
} 
+0

你可以嘗試'response.json()'而不是'response.ok'嗎? –

+0

response.json()返回_Promise {} _ – Konstantin

+0

好吧,我認爲這就是我需要的: _response.json()。然後()_返回我需要的。 非常感謝,大衛! – Konstantin

回答

1

你需要嘗試response.json()代替response.ok這將返回以適當的方式迴應你的情況。

希望這會有所幫助!