CORS POST请求抛出授权标头

时间:2016-11-07 11:08:15

标签: javascript ajax cors jestjs jsdom

我正在尝试向我的API发送CORS POST请求,并且每次使用“Authorization”标头时都会抛出TypeError。请求甚至没有被发送,因此服务器不参与。但这只发生在我的测试中。当我在Chrome中试用它时效果很好。

以下是我正在测试的功能:

export const postNewEmployee = formData => {
  return fetch('http://localhost:3003', {
                             method: 'POST',
                             headers: {
                               'Authorization': 'Bearer test123',
                               'Content-Type': 'application/json'
                             },
                             body: JSON.stringify(formData)
                           })
                           .then(response => response)
                           .catch(error => {
                             throw error;
                           });
  };

及其测试:

import * as API from './api';
describe('postNewEmployee', () => {

  it('posts the form data asynchronously', () => {

    let formData = {
      employee: {
        name: 'Test Person',
        email: 'test@person.nu',
        address: 'an adress 123'
      }
    };

    return API.postNewEmployee(formData)
      .then(json => {
        expect(json.status).toEqual(201);
      }).catch(error => {
        console.log(error);
      });
  });
});

该应用程序是使用create-react-app创建的react / redux应用程序,因此我使用Jest和JSDOM来测试它。问题是,如果我从fetch()调用注释掉Authorization标头,它就可以正常工作。但如果我添加标题,我会得到这个:

TypeError: Cannot convert undefined or null to object
    at Object.getRequestHeader (/Users/johanh/Kod/react-app/node_modules/react-scripts/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:20:23)
    at setDispatchProgressEvents (/Users/johanh/Kod/react-app/node_modules/react-scripts/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:909:38)
    at XMLHttpRequest.send (/Users/johanh/Kod/react-app/node_modules/react-scripts/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:700:11)
    at /Users/johanh/Kod/react-app/node_modules/react-scripts/node_modules/whatwg-fetch/fetch.js:429:11
    at Object.<anonymous>.self.fetch (/Users/johanh/Kod/react-app/node_modules/react-scripts/node_modules/whatwg-fetch/fetch.js:373:12)
    at Object.<anonymous>.exports.postNewEmployee.formData [as postNewEmployee] (/Users/johanh/Kod/react-app/src/api/api.js:20:10)
    at Object.it (/Users/johanh/Kod/react-app/src/api/api.test.js:75:16)
    at Object.<anonymous> (/Users/johanh/Kod/react-app/node_modules/react-scripts/node_modules/jest-jasmine2/build/jasmine-async.js:42:32)
    at attemptAsync (/Users/johanh/Kod/react-app/node_modules/react-scripts/node_modules/jest-jasmine2/vendor/jasmine-2.4.1.js:1919:24)
    at QueueRunner.run (/Users/johanh/Kod/react-app/node_modules/react-scripts/node_modules/jest-jasmine2/vendor/jasmine-2.4.1.js:1874:9)

正如我所说,这只发生在测试中。在浏览器中它工作正常。

我觉得我在这里遗漏了一些明显的东西,但我却看不到它。我查看了fetch规范和jsdom文档,但无济于事。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

通常,您不应该在单元测试中提出实际请求。处理此问题的最佳方法是使用模拟而不是真正的fetch实现。

我假设您正在使用fetch的JS实现。因此,您可以将fetch设置为您在测试中想要的内容。

import * as API from './api';
describe('postNewEmployee', () => {

  it('posts the form data asynchronously', () => {
    // set fetch to a mock that always returns a solved promise
    const fetch = jest.fn((url, options) => return Promise.resolve({status: 201}))
    global.fetch = fetch;
    let formData = {
      employee: {
        name: 'Test Person',
        email: 'test@person.nu',
        address: 'an adress 123'
      }
    };
    //test that fetch was called with the correct parameters
    expect(fetch.mock.calls[0][0]).toBe('http://localhost:3003')
    expect(fetch.mock.calls[0][1]).toEqual(formData)
    return API.postNewEmployee(formData)
      .then(json => {
        expect(json.status).toEqual(201);
      }).catch(error => {
        console.log(error);
      });
  });
});