Mar*_*vin 5 jestjs axios http-toolkit
从 node.js 中,这按预期工作,发送了 POST 响应(正如我使用 httpToolkit 验证的那样)
% node
> const axios = require('axios')
> var r = (async () => { const x = await axios.post('http://example.com/v1/secret/data/foo/bar/baz',{data: {foo: 42}},{headers: {'X-Special-Token': 'DATA'}}); return true;})().then(console.log)
undefined
> true
Run Code Online (Sandbox Code Playgroud)
但是,然后在测试中执行相同的操作jest,axios首先发送 OPTIONS 请求。我正在运行的服务无法处理该问题(不是 example.com)
const axios = require('axios');
describe('Simple Post', () => {
test('POST', async () => {
// Axios HERE seems to send an OPTIONS request first...
const x = await axios.post('http://example.com',
{data: {foo: 42}},
{headers: {'X-Special-Token': 'DATA'}});
expect(x.status).toBe(200);
});
});
Run Code Online (Sandbox Code Playgroud)
有没有什么方法可以说服/配置jest,或者axios这样就axios不会神奇地决定发送OPTIONS? 这与 CORS 无关——它的服务器代码与服务器代码对话,但显然有一些因素axios决定它是否合适。
通读这个问题,我的问题的解决方案就是下面的标题。请参阅 jest测试环境。这个问题确实有很多关于不同问题的讨论,所以 YMMV。
/**
* This is required to prevent axios from acting like it is in a browser
* environment and doing OPTIONS preflights, etc.
*
* @jest-environment node
*/
const axios = require('axios');
describe('Simple Post', () => {
test('POST', async () => {
// No preflight OPTIONS request sent when jest-environment is node
const x = await axios.post('http://example.com',
{data: {foo: 42}},
{headers: {'X-Special-Token': 'DATA'}});
expect(x.status).toBe(200);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1252 次 |
| 最近记录: |