问题
No matter what my server actually returns, Chai always gives me res.body={}
if the content-type is "application/javascript".
Here is my server:
const http = require('http');
const server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "application/javascript"});
response.end('console.log("test");');
});
module.exports = server;
server.listen(process.env.PORT || 8000);
console.log("Server running at http://localhost:8000/");
It outputs console.log("test");
:
But the test doesn't see it:
const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('./test-server');
const should = chai.should();
chai.use(chaiHttp);
describe('GET /test', () => {
it('it should give test result', (done) => {
chai.request(server)
.get('/test')
.end((err, res) => {
console.log(err);
console.log(res);
console.log(res.body); // {}
console.log(res.text); // undefined
res.body.should.be.eql('console.log("test");');
done();
});
});
});
res.body
works just fine when content-type is "application/json".
There also no trace of console.log("test");
string inside the response:
Response {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
res:
IncomingMessage {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: true,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: true,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Object],
data: [Function: bound emit],
close: [Function: bound emit],
error: [Function: bound emit] },
_eventsCount: 4,
_maxListeners: undefined,
socket:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 9,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 130,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Object],
read: [Function],
_consuming: true },
connection:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 9,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 130,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Object],
read: [Function],
_consuming: true },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: false,
headers:
{ 'content-type': 'application/javascript',
date: 'Mon, 10 Apr 2017 13:02:37 GMT',
connection: 'close',
'transfer-encoding': 'chunked' },
rawHeaders:
[ 'Content-Type',
'application/javascript',
'Date',
'Mon, 10 Apr 2017 13:02:37 GMT',
'Connection',
'close',
'Transfer-Encoding',
'chunked' ],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '',
method: null,
statusCode: 200,
statusMessage: 'OK',
client:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 9,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 130,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Object],
read: [Function],
_consuming: true },
_consuming: false,
_dumped: false,
req:
ClientRequest {
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedHeader: {},
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [Object],
connection: [Object],
_header: 'GET /test HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: node-superagent/2.3.0\r\nConnection: close\r\n\r\n',
_headers: [Object],
_headerNames: [Object],
_onPendingData: null,
agent: [Object],
socketPath: undefined,
timeout: undefined,
method: 'GET',
path: '/test',
_ended: false,
res: [Circular],
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: [Object],
maxHeadersCount: null } },
request:
Test {
domain: null,
_events: { end: [Function: bound _clearTimeout] },
_eventsCount: 1,
_maxListeners: undefined,
_agent: false,
_formData: null,
method: 'get',
url: 'http://127.0.0.1:8000/test',
_header: { 'user-agent': 'node-superagent/2.3.0' },
header: { 'User-Agent': 'node-superagent/2.3.0' },
writable: true,
_redirects: 0,
_maxRedirects: 5,
cookies: '',
qs: {},
qsRaw: [],
_redirectList: [],
_streamRequest: false,
app:
Server {
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 0,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::8000' },
req:
ClientRequest {
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedHeader: {},
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [Object],
connection: [Object],
_header: 'GET /test HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: node-superagent/2.3.0\r\nConnection: close\r\n\r\n',
_headers: [Object],
_headerNames: [Object],
_onPendingData: null,
agent: [Object],
socketPath: undefined,
timeout: undefined,
method: 'GET',
path: '/test',
_ended: false,
res: [Object],
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: [Object],
maxHeadersCount: null },
protocol: 'http:',
host: '127.0.0.1:8000',
_callback: [Function],
res:
IncomingMessage {
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
socket: [Object],
connection: [Object],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: false,
headers: [Object],
rawHeaders: [Object],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '',
method: null,
statusCode: 200,
statusMessage: 'OK',
client: [Object],
_consuming: false,
_dumped: false,
req: [Object] },
response: [Circular],
_timeout: 0,
called: true },
req:
ClientRequest {
domain: null,
_events:
{ drain: [Function],
error: [Function],
response: [Function],
prefinish: [Function: requestOnPrefinish] },
_eventsCount: 4,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedHeader: {},
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 9,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 130,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Circular],
read: [Function],
_consuming: true },
connection:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 9,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 130,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Circular],
read: [Function],
_consuming: true },
_header: 'GET /test HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: node-superagent/2.3.0\r\nConnection: close\r\n\r\n',
_headers:
{ host: '127.0.0.1:8000',
'accept-encoding': 'gzip, deflate',
'user-agent': 'node-superagent/2.3.0' },
_headerNames:
{ host: 'Host',
'accept-encoding': 'Accept-Encoding',
'user-agent': 'User-Agent' },
_onPendingData: null,
agent:
Agent {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 80,
protocol: 'http:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256 },
socketPath: undefined,
timeout: undefined,
method: 'GET',
path: '/test',
_ended: false,
res:
IncomingMessage {
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
socket: [Object],
connection: [Object],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: false,
headers: [Object],
rawHeaders: [Object],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '',
method: null,
statusCode: 200,
statusMessage: 'OK',
client: [Object],
_consuming: false,
_dumped: false,
req: [Circular] },
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': null,
_headers: [],
_url: '',
_consumed: false,
socket: [Object],
incoming: [Object],
outgoing: [Circular],
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncomingClient] },
maxHeadersCount: null },
links: {},
text: undefined,
body: {},
files: undefined,
buffered: false,
headers:
{ 'content-type': 'application/javascript',
date: 'Mon, 10 Apr 2017 13:02:37 GMT',
connection: 'close',
'transfer-encoding': 'chunked' },
header:
{ 'content-type': 'application/javascript',
date: 'Mon, 10 Apr 2017 13:02:37 GMT',
connection: 'close',
'transfer-encoding': 'chunked' },
statusCode: 200,
status: 200,
statusType: 2,
info: false,
ok: true,
redirect: false,
clientError: false,
serverError: false,
error: false,
accepted: false,
noContent: false,
badRequest: false,
unauthorized: false,
notAcceptable: false,
forbidden: false,
notFound: false,
type: 'application/javascript',
setEncoding: [Function: bound ],
redirects: [] }
How do I assert the response when the content-type is "application/json"?
回答1:
Update 21 May 2019
You must add .buffer(true)
in your test in order for chai to understand.
const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('./server');
const should = chai.should();
chai.use(chaiHttp);
describe('GET /test', () => {
it('it should give test result', (done) => {
chai.request(server)
.get('/test')
.buffer(true)
.end((err, res) => {
console.log(err);
// console.log(res);
console.log(res.application);
console.log(res.body); // {}
console.log(res.text); // undefined
res.text.should.be.eql('console.log("test");');
done();
});
});
});
Then, req.text
will have the content console.log("test")
.
If you assert on req.text
instead of req.body
, it will work.
See github issue: https://github.com/chaijs/chai-http/issues/249
Kudos to @Dante for noticing the deprecated content-type.
Original Post
First set 'text/javascript'
instead of 'application/javascript'
.
Then, req.text
will have the content console.log("test")
.
If you assert on req.text
instead of req.body
, it will work.
来源:https://stackoverflow.com/questions/43324004/chai-doesnt-recognize-content-type-application-javascript