我正在为一个简单的 NodeJS 应用程序编写单元测试,由于某种原因我无法检索响应正文。它获得正确的响应代码(成功请求为 200,无效请求为 422),但正文似乎为空。另外,当我使用 httpie 发出完全相同的请求时,它就像魅力一样。日志记录还显示 Controller 按预期工作。
欢迎任何想法或建议。
这是 Controller 部分:
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...}
}
最佳答案
您需要尝试 response.json()
而不是 response.ok
,它将根据您的情况以正确的方式返回响应。
希望这有帮助!
关于javascript - node-fetch 接收空主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39932050/