Jest 测不到 uuid

使用 jest没办法测到uuid,

  • 方案一

因此我才用了jest的mock方法,因为我只用了v4这个function, 所以我这么写的

jest.mock("uuid", () => {
  return {
    v4: () => 123456789,
  };
});

然后就没报错了

当前jest版本 babel-jest ts-jest jest 都是28.0.X

  • 方案二

然后在jest github找到了更靠谱点的解决方案: 自定义resolver

 这是resolver

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

module.exports = (path, options) => {
    // Call the defaultResolver, so we leverage its cache, error handling, etc.
    return options.defaultResolver(path, {
        ...options,
        // Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb)
        packageFilter: pkg => {
            // This is a workaround for https://github.com/uuidjs/uuid/pull/616
            //
            // jest-environment-jsdom 28+ tries to use browser exports instead of default exports,
            // but uuid only offers an ESM browser export and not a CommonJS one. Jest does not yet
            // support ESM modules natively, so this causes a Jest error related to trying to parse
            // "export" syntax.
            //
            // This workaround prevents Jest from considering uuid's module-based exports at all;
            // it falls back to uuid's CommonJS+node "main" property.
            //
            // Once we're able to migrate our Jest config to ESM and a browser crypto
            // implementation is available for the browser+ESM version of uuid to use (eg, via
            // https://github.com/jsdom/jsdom/pull/3352 or a similar polyfill), this can go away.
            if (pkg.name === 'uuid') {
                delete pkg['exports'];
                delete pkg['module'];
            }
            return pkg;
        },
    });
};

然后在jest.config  文件中配置resolver

 resolver: `${__dirname}/src/tests/common/resolver.js`,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值