Chai无法识别内容类型为

Chai无法识别内容类型为

本文介绍了Chai无法识别内容类型为"application/javascript"的内容,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论我的服务器实际返回什么,如果内容类型为"application/javascript",Chai总是会给我res.body={}.

No matter what my server actually returns, Chai always gives me res.body={} if the content-type is "application/javascript".

这是我的服务器:

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/");

它输出console.log("test");:

但是测试看不到:

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在content-type为"application/json"时可以正常工作.

res.body works just fine when content-type is "application/json".

响应中也没有跟踪console.log("test");字符串:

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: [] }

当内容类型为"application/json"时,如何断言响应?

How do I assert the response when the content-type is "application/json"?

推荐答案

2019年5月21日更新

您必须在测试中添加.buffer(true),以使chai理解.

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();
      });
  });
});

然后,req.text将具有内容console.log("test").

如果您在req.text而不是req.body上声明,它将起作用.

If you assert on req.text instead of req.body, it will work.

请参阅github问题: https://github.com/chaijs/chai-http/issues/249

See github issue:https://github.com/chaijs/chai-http/issues/249

对@Dante表示敬意,以注意到已弃用的内容类型.

Kudos to @Dante for noticing the deprecated content-type.

原始帖子

首先设置'text/javascript'而不是'application/javascript'.

然后,req.text将具有内容console.log("test").

如果您在req.text而不是req.body上声明,它将起作用.

If you assert on req.text instead of req.body, it will work.

这篇关于Chai无法识别内容类型为"application/javascript"的内容,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:07