由于Webpack中的CSS,Mocha测试失败

我是Mocha的新手,我正在尝试使用它来测试一个简单的React组件。如果react组件没有任何CSS样式,则测试将通过,但是如果React组件内的标签包含任何className,则会引发语法错误:

Testing.react.js

import React from 'react';

export default class Testing extends React.Component {
  render() {
    return (
      <section>
        <form>
          <input type="text" />
        </form>
      </section>
    );
  }
}

testing.jsx

import {
  React,
  sinon,
  assert,
  expect,
  TestUtils
} from '../../test_helper';

import TestingSample from '../../../app/components/Testing.react.js';

describe('TestingSample component', function(){
    before('render and locate element', function(){
        var renderedComponent = TestUtils.renderIntoDocument(
            <TestingSample />
        );

        var inputComponent = TestUtils.findRenderedDOMComponentWithTag(
            renderedComponent, 'input'
        );

        this.inputElement = inputComponent.getDOMNode();
    });

    it('<input> should be of type "text"', function () {
        assert(this.inputElement.getAttribute('type') === 'text');
    });
})

测试将通过:

> mocha --opts ./test/javascripts/mocha.opts --compilers js:babel/register --recursive test/javascripts/**/*.jsx


  TestSample component
    ✓ <input> should be of type "text"


  1 passing (44ms)

在输入标签内添加className之后,出现错误:

import React from 'react';
import testingStyle from '../../scss/components/landing/testing.scss';

export default class Testing extends React.Component {
  render() {
    return (
      <section>
        <form>
          <input type="text" className="testingStyle.color" placeholder="Where would you like to dine" />     
        </form>
      </section>
    );
  }
}

测试结果:

SyntaxError: /Users/../../../Documents/project/app/scss/components/landing/testing.scss: Unexpected token (1:0)
> 1 | .color {
    | ^
  2 |   color: red;
  3 | }

我已经在网上搜索过,但到目前为止还没有运气。我想念什么吗?请帮助我或指出正确的方向,将不胜感激。我当前正在使用:
Node Express Server
React
React-router
Webpack
Babel
Mocha
Chai
Sinon
Sinon-Chai

米亚宝儿2020/03/16 15:20:32

对于那些希望在其中处理的人,jest您只需为样式文件添加处理程序即可:

// package.json
{
  "jest": {
    "moduleNameMapper": {
      "\\.(css|less|scss|sass)$": "<rootDir>/__mocks__/styleMock.js"
    }
  }
}

// __mocks__/styleMock.js
module.exports = {};

这里更多

卡卡西达蒙2020/03/16 15:20:32

一种简单的方法是导入“忽略样式”。在您的测试课程中..

JimTom2020/03/16 15:20:31

有一个babel/register样式挂钩可以忽略样式导入:

https://www.npmjs.com/package/ignore-styles

安装它:

npm install --save-dev ignore-styles

运行没有样式的测试:

mocha --require ignore-styles