【问题标题】:Solve Jest test error from Webpack plugin解决来自 Webpack 插件的 Jest 测试错误
【发布时间】:2020-02-24 19:04:33
【问题描述】:

我有一个 webpack 配置文件,其中包含一些配置字符串,例如:

const config={
    'accessUrl': 'http://localhost:8000/links',
    'firstAuthUrl': 'http://localhost:8000/firstAccess',
    'baseUrl': '/video?url=',
    'urlRefreshToken': 'http://localhost:8000/refreshAccessToken',
    'loginUrl': 'http://localhost:8000/login',
    'userUrl':'http://localhost:8000/user'
}

module.exports = merge(common, {
    mode: 'development',
    devtool: 'inline-source-map',
    devServer: {
        contentBase: './dist',
        historyApiFallback: true,
        hot: true,
    },
    plugins: [
        new DefinePlugin({
            'config': JSON.stringify(config)
        }),
    ],
});

没关系,但是当我向一个内部使用配置的组件添加一个玩笑测试(见上文)时,它不起作用,因为它无法识别配置。

组件的部分是:

<a href={config.baseUrl} className='btn btn-outline-warning justify-content-center mt-5'>

当我启动应用程序时它可以工作,但是当我编写和启动测试时:

describe('Content Component', () => { 
  const content = shallow(<Content {...props}/>); expect(content.render); 
  expect(content.find('.content')).toBeDefined(); 
})

测试运行时说:ReferenceError: config is not defined

我该如何解决?

非常感谢。

【问题讨论】:

  • 对不起,组件部分是:
  • 它不起作用?它实际上说的是什么? Unexpected token 之类的东西?

标签: reactjs webpack jestjs


【解决方案1】:

Jest 实际上不使用 webpack,它的配置。因此DefinePlugin 无法为 Jest 提供config 并导致您提到的错误。

要解决此问题,您必须在 globals 下的 Jest 配置中提供与 DefinePlugin 相同的配置。参考:https://jestjs.io/docs/en/configuration.html#globals-object

示例jest 配置:

const { jsWithTs: tsjPreset } = require('ts-jest/presets');
module.exports = {
    roots: ['<rootDir>/app'],
    moduleDirectories: ['node_modules', 'app'],
    transform: {
        ...tsjPreset.transform,
    },
    testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
    globals: {
        config: *YOUR_CONFIG_HERE*
    },
};

【讨论】:

  • 你有什么例子吗?
  • 更新的答案导致格式在 cmets 中不起作用。
【解决方案2】:

好的,我通过添加 setupTest.js 文件来解决,例如:

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { shallow, render, mount } from 'enzyme';

configure({ adapter: new Adapter() });


const config = {
    baseUrl:""
};

global.shallow = shallow;
global.render = render;
global.mount = mount;
global.config = config;

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 2017-12-14
    • 2021-04-17
    • 2019-10-25
    • 2017-01-31
    • 2015-10-11
    • 2017-01-22
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多