我为一个简单的NodeJS应用程序编写单元测试,由于某种原因,我无法检索响应体。它获得了正确的响应代码(成功请求为200或无效请求为422)但是正文似乎是空的。此外,当我使用 httpie 制作完全相同的请求时,它就像魅力一样。记录还显示控制器按预期工作。
欢迎任何想法或建议。
以下是控制器部分:
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: 'test@test.com', 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="rest@test.com" 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)
从 fetch()中打印出响应正文显示了一些巨大的对象:
PassThrough {
_readableState:
ReadableState {etc...}
}
答案 0 :(得分:1)
您需要尝试response.json()
而不是response.ok
,这会在您的情况下以适当的方式返回响应。
希望这有帮助!