【问题标题】:React CSS Modules and testing the componentReact CSS Modules 和测试组件
【发布时间】:2017-10-10 23:10:42
【问题描述】:

在我的代码中,我使用 babel-plugin-react-css-modules,它实际上与 react-css-modules 相同

我在 react 组件中有这样的代码。 styleName 用于 CSS 模块,我在 countdownForm.local.scss 中为它们定义样式 className 代表我的 Bootstrap 类

import './countdownForm.local.scss'

class CountdownForm extends Component {
...
render () {
    return (
      <div styleName="first" className="container">
        ...
      </div>
    )
  }
}

要在我的测试中测试这个组件,我必须使用 ignore-styles 包,因为 JavaScript 无法处理 CSS 语法,当我们运行单元测试时,测试将尝试在没有 Webpack 的情况下导入 CSS 文件,这将导致错误。

import register from 'ignore-styles'
import React from 'react'
import test from 'tape'
import CountdownForm from 'CountdownForm'

register(undefined, () => ({styleName: 'fake_class_name'}))

test('CountdownForm => should exist', (t) => {
  t.ok(CountdownForm)
  t.end()
})

通过这样做,一切顺利,测试工作没有问题,但我总是在控制台中收到此警告

警告:标签上的未知道具 styleName。从 元素。

这不是功能问题,因为测试有效,但每次运行测试时都收到此消息很烦人。如何解决,摆脱它?

【问题讨论】:

    标签: reactjs testing css-modules


    【解决方案1】:

    警告是因为您没有在测试前运行babel-plugin-react-css-modules 编译步骤。

    这可以通过将 styleName 属性替换为计算出的 CSS 模块类名来实现。因此,styleName 从未真正传递给您实际构建中的 div (https://github.com/gajus/babel-plugin-react-css-modules#how-does-it-work)。它会将您的组件重写为...

    class CountdownForm extends Component {
      ...
      render () {
        return (
          <div className="container CountdownForm_first_123xyz">
            ...
          </div>
        )
      }
    }
    

    在您的测试中,如果不先运行 babel 插件,您将成功地通过 ignore-styles 忽略 CSS 导入,但道具替换尚未发生,因此您最终将 styleName 道具传递给 div , 这不是 div 组件的定义属性,所以 React 会警告你

    解决此问题的最佳方法是在测试之前运行 babel 编译步骤,这样您还可以测试真正的本地化类名分配

    【讨论】:

    • 嗨,阿莱奇。这很有意义,但是我如何在测试之前运行babel-plugin-react-css-modules。它在 webpack 中定义,而测试在 webpack 包之外。我使用脚本"test": "babel-tape-runner \"test/setup.js\" \"test/**/*test.jsx\" | node_modules/.bin/tap-summary" 运行测试在设置中我只需要jsdom 和ignore-styles。我喜欢在代码中包含 styleName 和 className 以轻松区分和自定义两者。
    • 那么跑步者应该首先通过 babel 管道(使用 .babelrc 进行配置),所以我会确保你在该文件中定义了所有必要的插件 { "plugins": ["babel-plugin-react-css-modules"] }
    • alechill 我试过了,但没有运气。我在上面回答了我的 .babelrc 和 webpack 的样子。
    猜你喜欢
    • 1970-01-01
    • 2018-04-08
    • 2020-05-01
    • 2018-05-17
    • 2016-12-16
    • 2018-10-06
    • 2017-02-11
    • 2017-02-12
    • 2018-04-04
    相关资源
    最近更新 更多