我可以将 Enzyme 的 .hasClass 功能与导入 css 文件的 react 组件一起使用吗? [英] Can i use Enzyme's .hasClass feature with react components importing css files?

查看:39
本文介绍了我可以将 Enzyme 的 .hasClass 功能与导入 css 文件的 react 组件一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在设置一个测试环境并遇到一个问题,我对 .hasClass 的所有调用都返回 false.

i am currently setting up a test environment and come across a problem, that all my calls to .hasClass return false.

当前设置:我的 react 组件使用 import 语句导入 scss 文件.例如:从./text.scss"导入样式;

Current Setup: My react components import scss files with an import statement. For example: import styles from "./text.scss";

为了测试组件,我必须在 jest.config.js 文件中定义 moduleNameMapper,如下所示:

To test the components i had to define the moduleNameMapper in the jest.config.js file like so:

moduleNameMapper: { "\\.(scss|less)$": "/__mocks__/styleMock.js" },

我认为 moduleNameMapper 对这些问题负有责任,因为它默认使用空模块替换了所有 scss 定义.(styleMock.js 内容只是 module.exports = {};)但是我需要它来测试我的组件,否则当 jest 尝试加载 scss 导入时会导致错误.

I think that the moduleNameMapper is kind of responsible for the problems, since it replaces via default all scss definitions with an empty module. (styleMock.js content is just module.exports = {};) But i need it to test my components, otherwise it would result in an error, when jest tries to load the scss imports.

当我现在尝试这个时:

 it("is Title", () => {
    const wrapper = shallow(<Text textType={TextType.Title} />);
    expect(wrapper.find("div").hasClass("Title")).toEqual(true);
  });

它总是返回 false.

It always returns false.

当您的组件中有 scss 导入语句时,是否有关于如何测试 scss 类(使用 .hasClass 来自酶?)的解决方案?

Is there any solultion on how to test the scss classes (with .hasClass from enzyme?), when you have scss import statements in your component?

推荐答案

终于找到了有效的解决方案!

Found a solution finally that works!

对我来说,我必须通过以下方式安装 identity-obj-proxynpm install --save-dev identity-obj-proxy然后将其添加到 jest 配置文件中,如下所示:

For me i had to install the identity-obj-proxy via npm install --save-dev identity-obj-proxy and then add it to the jest config file like that:

moduleNameMapper: {
    "^.+\\.(css|less|scss)$": "identity-obj-proxy"
  }

在那之后,我的类名现在正确地出现在快照中,不再有未定义的类名!除此之外,我现在终于可以使用酶的 .hasClass 功能并检查新的 css 类是否已添加到 div 等等.(我终于可以开始测试那些条件渲染部分了!)

After that my class name's are now in the snapshots correctly and no more undefined classnames! In addition to that i can now finally use the .hasClass feature of enzyme and check if new css class had been added to a div and so on. (Finally i can go into testing those conditional rendering parts!)

这篇关于我可以将 Enzyme 的 .hasClass 功能与导入 css 文件的 react 组件一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆