简体   繁体   中英

Response for preflight has invalid HTTP status code 401 - Testing

so i'm using nodejs to access an API ( league of legend api ) from my server, i tested the route that access the api using httpie ( a simple http client) and everything is working without any issue.

when i wanted to write tests for my api using Jest + supertest , and when i tested the route that access the remote LOL api , a always get this error

Response for preflight has invalid HTTP status code 401

of course i never get this error when i'm using the http client or a webbrowser

Test Method

 test('exist route should return 200 if summoner exist', done => {
        request(app)
            .get('/summoners/exist/yaskillin')
            .expect('Content-Type', /json/)
            .expect(200)
            .then(res => {
                expect(res.body.exist).toBeTruthy()
                done()
            })
    })

Route Method

private exist(req: Request, res: Response, next: NextFunction) {
    let name: string = req.params["name"];


    return this.riotService
      .getSummonerByName(name)
      .then(result => {
          console.log(result)
          res.json({ exist: true });
      })
      .catch(err => {
          console.log(err.config)
          res.json({ exist: false });
      });
  }

Error

console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Error: Response for preflight has invalid HTTP status code 401
        at Object.dispatchError (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
        at EventEmitter.client.on.err (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:664:20)
        at EventEmitter.emit (events.js:185:15)
        at Request.preflightClient.on.resp (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:373:16)
        at Request.emit (events.js:180:13)
        at Request.onRequestResponse (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/request/request.js:1068:10)
        at ClientRequest.emit (events.js:180:13)
        at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:539:21)
        at HTTPParser.parserOnHeadersComplete (_http_common.js:117:17)
        at TLSSocket.socketOnData (_http_client.js:444:20) undefined

Error Object

{ Error: Network Error
        at createError (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/axios/lib/core/createError.js:16:15)
        at XMLHttpRequest.handleError (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/axios/lib/adapters/xhr.js:87:14)
        at XMLHttpRequest.el.addEventListener.event (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/helpers/create-event-accessor.js:33:32)
        at invokeEventListeners (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:193:27)
        at XMLHttpRequestEventTargetImpl._dispatch (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:119:9)
        at XMLHttpRequestEventTargetImpl.dispatchEvent (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:82:17)
        at XMLHttpRequest.dispatchEvent (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:21)
        at requestErrorSteps (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:132:7)
        at Object.dispatchError (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:62:3)
        at EventEmitter.client.on.err (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:664:20)
        at EventEmitter.emit (events.js:185:15)
        at Request.preflightClient.on.resp (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:373:16)
        at Request.emit (events.js:180:13)
        at Request.onRequestResponse (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/request/request.js:1068:10)
        at ClientRequest.emit (events.js:180:13)
        at HTTPParser.parserOnIncomingClient (_http_client.js:539:21)
        at HTTPParser.parserOnHeadersComplete (_http_common.js:117:17)
        at TLSSocket.socketOnData (_http_client.js:444:20)
        at TLSSocket.emit (events.js:180:13)
        at addChunk (_stream_readable.js:269:12)
        at readableAddChunk (_stream_readable.js:256:11)
        at TLSSocket.Readable.push (_stream_readable.js:213:10)
        at TLSWrap.onread (net.js:581:20)
      config: 
       { adapter: [Function: xhrAdapter],
         transformRequest: { '0': [Function: transformRequest] },
         transformResponse: { '0': [Function: transformResponse] },
         timeout: 0,
         xsrfCookieName: 'XSRF-TOKEN',
         xsrfHeaderName: 'X-XSRF-TOKEN',
         maxContentLength: -1,
         validateStatus: [Function: validateStatus],
         headers: 
          { Accept: 'application/json, text/plain, */*',
            'Accept-Charset': 'application/x-www-form-urlencoded; charset=UTF-8',
            'X-Riot-Token': 'RGAPI-3467f48f-6e15-4bb2-8ebf-8d2acecac233',
            'Accept-Language': 'en-US,en;q=0.9,fr;q=0.8' },
         method: 'get',
         baseURL: 'https://euw1.api.riotgames.com/lol/',
         url: 'https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/yaskillin',
         data: undefined },
      request: 
       XMLHttpRequest {
         upload: XMLHttpRequestUpload { _ownerDocument: [Document] },
         _registeredHandlers: Set { 'readystatechange' },
         _eventHandlers: { readystatechange: [Function: handleLoad] },
         [Symbol(flag)]: 
          { synchronous: false,
            withCredentials: false,
            mimeType: null,
            auth: null,
            method: 'GET',
            responseType: '',
            requestHeaders: [Object],
            referrer: 'about:blank',
            uri: 'https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/yaskillin',
            timeout: 0,
            body: undefined,
            formData: false,
            preflight: true,
            requestManager: [RequestManager],
            pool: undefined,
            agentOptions: undefined,
            strictSSL: undefined,
            proxy: undefined,
            cookieJar: [CookieJar],
            encoding: 'UTF-8',
            origin: 'null',
            userAgent: 'Mozilla/5.0 (linux) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/11.6.2' },
         [Symbol(properties)]: 
          { beforeSend: false,
            send: false,
            timeoutStart: 0,
            timeoutId: 0,
            timeoutFn: null,
            client: [EventEmitter],
            responseHeaders: {},
            filteredResponseHeaders: [],
            responseBuffer: null,
            responseCache: null,
            responseTextCache: null,
            responseXMLCache: null,
            responseURL: '',
            readyState: 4,
            status: 0,
            statusText: '',
            error: Error: Response for preflight has invalid HTTP status code 401
        at Request.preflightClient.on.resp (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:373:30)
        at Request.emit (events.js:180:13)
        at Request.onRequestResponse (/home/ssd/Dev/Project/lolnafrica/backend/node_modules/request/request.js:1068:10)
        at ClientRequest.emit (events.js:180:13)
        at HTTPParser.parserOnIncomingClient (_http_client.js:539:21)
        at HTTPParser.parserOnHeadersComplete (_http_common.js:117:17)
        at TLSSocket.socketOnData (_http_client.js:444:20)
        at TLSSocket.emit (events.js:180:13)
        at addChunk (_stream_readable.js:269:12)
        at readableAddChunk (_stream_readable.js:256:11),
            uploadComplete: true,
            uploadListener: false,
            abortError: false,
            cookieJar: [CookieJar],
            bufferStepSize: 1048576,
            totalReceivedChunkSize: 0,
            requestBuffer: null,
            requestCache: null,
            origin: 'null' } },
      response: undefined }

SOLVED --

by default, jest is runner in jsdom mode, that mean that jest is runner in a browser like envirement by default,

what need to be done is to configure it to run in server like envirement you need to put that in your jest.config file

"testEnvironment": "node",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM