【问题标题】:p-retry making my test unlaunchable wonder why and how to fix thatp-retry 使我的测试无法启动想知道为什么以及如何解决这个问题
【发布时间】:2022-08-08 20:47:28
【问题描述】:

所以我的问题是,因为我实现了 p-retry 库(重试调用 api X 次你想要)。在localhost:3000 上工作正常,但是当我启动测试时,我得到了以下回报:

  ● 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 :

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

我尝试了很多不同的配置和实现,但无事可做......仍然是同样的错误,所以我想知道问题是否可能是其他问题。 可以肯定的是,因为我使用 p-retry 将 axios 更改为 node-fetch (以处理请求并重试),所以我的测试刚刚停止工作

    标签: javascript jestjs


    【解决方案1】:

    我来为与我遇到相同问题的人提供解决方案。所以我没有修复 lib 或找到 jest config 来处理奇怪的行为,所以我创建了自己的函数来做同样的事情:

    • 如果达到超时,这将调用 X 次相同的调用 api

    代码 :

    const makeAPICall = async ({
        url,
        body = '',
        method = 'GET',
        type = 'TEXT',
    }: IMedvirApi) => {
        // 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',
        }); 
    

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 2021-01-10
      • 2011-12-03
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      相关资源
      最近更新 更多