首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >P-重试使我的测试无法启动,不知道为什么以及如何修复它。

P-重试使我的测试无法启动,不知道为什么以及如何修复它。
EN

Stack Overflow用户
提问于 2022-07-26 13:41:41
回答 1查看 110关注 0票数 0

因此,我的问题是,由于我实现了p-retry lib (重试调用api X次您想要的)。在localhost:3000上工作很好,但是当我启动测试时,我得到了以下返回:

代码语言:javascript
复制
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /project/node_modules/p-retry/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import retry from 'retry';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import fetch from 'node-fetch';
    > 2 | import pRetry, { AbortError } from 'p-retry';
        | ^
      3 |
      4 | import HttpsProxyAgent from 'https-proxy-agent';
      5 | const proxyAgent = process.env.HTTPS_PROXY

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (services/medVir/http.ts:2:1)

所以我想这可能是配置错误,所以这是我的jest.config.js:

代码语言:javascript
复制
const nextJest = require('next/jest');

const createJestConfig = nextJest({
    // Provide the path to your Next.js app to load next.config.js and .env.local files in your test environment
    dir: './',
});

// Add any custom config to be passed to Jest
const customJestConfig = {
    clearMocks: true,
    collectCoverage: true,
    coverageDirectory: 'coverage',
    coveragePathIgnorePatterns: [
        '/node_modules/',
        '__tests__/utils/',
        '/public/',
    ],
    moduleNameMapper: {
        '\\.(css|less)$': 'identity-obj-proxy',
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
            'identity-obj-proxy',
        '^-!svg-react-loader.*$': '<rootDir>/config/jest/svgImportMock.js',
    },
    testEnvironment: 'jsdom',
    testMatch: [
        // "**/__tests__/**/*.[jt]s?(x)",
        '**/?(*.)+(spec|test).[tj]s?(x)',
    ],
    testPathIgnorePatterns: ['/node_modules/', '__tests__/utils/'],
    // transformIgnorePatterns: ['node_modules/(?!(p-retry)/)'],
    verbose: true,
    transform: {
        // Use babel-jest to transpile tests with the next/babel preset
        // https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
        '^.+\\.(js|jsx|ts|tsx)$': [
            'babel-jest',
            {
                presets: [
                    [
                        '@babel/preset-env',
                        {
                            targets: {
                                node: 'current',
                            },
                        },
                    ],
                    '@babel/preset-typescript',
                    '@babel/preset-react',
                ],
            },
        ],
    },
    setupFiles: ['<rootDir>/.jest/setEnvVars.js'],
    setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
// module.exports = customJestConfig;
module.exports = createJestConfig(customJestConfig);

我尝试了很多不同的配置和实现,但什么也没做.仍然是同样的错误,所以我想知道问题是否可能是其他原因。可以肯定的是,由于我将axios更改为节点-用p-retry (处理请求然后重试)获取节点,我的测试就停止工作了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-08 12:47:28

我是来给你一个解决和我一样问题的人的解决方案的。因此,我没有修复lib或找到jest配置来处理奇怪的行为,所以我创建了自己的函数来做类似的事情:

  • ,如果超时到达

,它将召回X倍相同的调用api。

代码:

代码语言:javascript
复制
const makeAPICall = async ({
    url,
    body = '',
    method = 'GET',
    type = 'TEXT',
}: IApi) => {
    // init path
    const path = new URL(url);
    const timeout = 28_000;
    let myInit = {
        method,
        timeout,
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
    };
    if (method !== 'GET') myInit = { ...myInit, ...{ body: body } };
    const res = await fetch(path.href, myInit);
    switch (type) {
        case 'TEXT':
            return res.text();
        default:
            return res.json();
    }
};

const sleep = (ms: number) =>
    new Promise((resolve) => setTimeout(() => resolve(), ms));

const makeApiRetry: any = async (args: IArgs, retries = 3, old_n = 0) => {
    let n = old_n;

    return makeAPICall(args).catch(async () => {
        if (n < retries) {
            n++;
            // console.log('Retrying request', n, `waiting ${1000 * n} `, args.url);
            await sleep(1000 * (n + 1));
            return makeApiRetry(args, retries, n);
        } else {
            return Promise.reject('Too many retries : error timeout');
        }
    });
};

// Get node-fectch
export const getApiRoute = async (body: string) =>
    await makeApiRetry({
        url: `/apiRoute`,
        body,
        method: 'GET',
        type: 'JSON',
    }); 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73124491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档