Program Tip

웹팩의 CSS로 인해 모카 테스트 실패

programtip 2020. 10. 31. 10:02
반응형

웹팩의 CSS로 인해 모카 테스트 실패


저는 Mocha를 처음 사용하며 간단한 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


babel/register스타일 가져 오기를 무시 하는 스타일 후크가 있습니다.

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

그것을 설치하십시오 :

npm install --save-dev ignore-styles

스타일없이 테스트 실행 :

mocha --require ignore-styles


다음과 같이 컴파일러 js 인 mocha를 실행하는 css 컴파일러를 사용할 수 있습니다.

css-dnt-compiler.js

function donothing() {
  return null;
}

require.extensions['.css'] = donothing;
require.extensions['.less'] = donothing;
require.extensions['.scss'] = donothing;
// ..etc

다음과 같이 mocha 명령을 실행합니다.

mocha --compilers js:babel-core/register,css:css-dnt-compiler.js --recursive

여기와 같은 대답 , 이것이 Babel 6에서 작업하는 데 사용했던 것입니다.

package.json

"scripts": {
  "test": "mocha --compilers js:babel-core/register 
          --require ./tools/testHelper.js 'src/**/*-spec.@(js|jsx)'",

tools / testHelper.js

// Prevent mocha from interpreting CSS @import files
function noop() {
  return null;
}

require.extensions['.css'] = noop;

이를 통해 구성 요소와 함께 src 폴더에 테스트를 둘 수 있습니다. require.extensions를 사용하여 원하는만큼 확장을 추가 할 수 있습니다.


웹팩을 사용하고 있으므로 웹팩이 구성 요소에서 필요한 CSS / LESS / SASS / etc 파일을 발견 할 때로드 하려면 null-loader사용 null하십시오. npm을 통해 설치 한 다음 로더를 포함하도록 웹팩 구성을 업데이트하십시오.

{
    test: /(\.css|\.less|.\scss)$/,
    loader: 'null-loader'
}

Obviously this will prevent you from loading CSS in your actual application, so you'll want to have a separate webpack config for your test bundle that uses this loader.


None of these solutions worked for me, as I'm using mocha-webpack, and it doesn't accept the "--compilers" switch. I implemented the ignore-styles package, as described in the most popular answer, but it seemed inert, with no difference in my Istanbul coverage report (.less files still being tested).

The problem is the .less loader that I was using in my webpack.config.test.js file. Simply swapping less-loader for null-loader fixed my problem.

module: {
    rules: [
        {
            test: /\.less$/,
            use: ['null-loader']
        }
    ]
}

For me, this is by far the simplest solution, and targets my testing configuration directly, rather than having to alter/add to the package.json scripts, or worse, add new .js files.


For those looking how to handle this in jest - you just add a handler for style files:

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

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

More here.


One simple way is to import 'ignore-styles'; in your test classes..


The code below works without any dependencies. Just add it to the top of the tests.

var Module = require('module');
var originalRequire = Module.prototype.require;
Module.prototype.require = function () {
    if (arguments[0] && arguments[0].endsWith(".css"))
        return;
    return originalRequire.apply(this, arguments);
};

Although very old, this question is still relevant, so let me throw in another solution.

Use pirates, a package to add hooks to require() - if you use Babel, you already have it.

Example code:

// .test-init.js
const { addHook } = require('pirates');

const IGNORE_EXTENSIONS = ['.scss', '.svg', '.css'];

addHook((code, filename) => '', { exts: IGNORE_EXTENSIONS });

This way you can call mocha like so: mocha --require .test-init.js [whatever other parameters you use]

This is straightforward, elegant and unlike ignore-styles it doesn't imply you are ignoring styles only. Also, this is easily extendable if you need to apply some more trickery to your tests like mocking entire modules.

참고URL : https://stackoverflow.com/questions/32236443/mocha-testing-failed-due-to-css-in-webpack

반응형