【问题标题】:Cannot import SCSS file while running mocha test on isomorphic app在同构应用程序上运行 mocha 测试时无法导入 SCSS 文件
【发布时间】:2015-11-26 16:51:51
【问题描述】:

我正在尝试测试一个反应组件。

Foo.jsx

import * as React from 'react';
require('css/foo'); // foo.scss but using resolve in the webpack

...rest of code

Foo.spec.js(这只是一个测试的锅炉)

import * as React from 'react';
import * as TestUtils from 'react-addons-test-utils';
import Foo from '../src/js/Foo';

function setup() {
  const renderer = TestUtils.createRenderer();
  renderer.render(<Menu />);
  const output = renderer.getRenderOutput();

  return {
    props: props,
    output: output,
    renderer: renderer
  }
}

describe('Menu Component', () => {
  it('should render', () => {
    setup();
  })
});

tests.js

function noop() {
  return null;
}

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

尝试从 CLI 加载 mocha 时

./node_modules/.bin/mocha tests.js ./test/**/*.spec.js

我遇到了一个错误

Error: Cannot find module 'css/foo' ...

我试过了: Handle WebPack CSS imports when testing with Mocha

但它也不起作用。

如果我注释掉该行,则测试正在执行。

【问题讨论】:

    标签: javascript reactjs mocha.js webpack


    【解决方案1】:

    我找到了解决方案。 https://github.com/darul75/web-react/blob/master/app/components/TodoSection/TodoItem.js#L13

    当我在服务器上运行测试时:

    APP_ENV=SERVER ./node_modules/.bin/mocha tests.js ./test/**/*.spec.js
    

    在客户端我必须在 webpack 配置中添加一个插件:

    plugins: [
      new webpack.DefinePlugin({
        'process.env': {
          'APP_ENV': JSON.stringify('BROWSER'),
         }
      })
    ]
    

    【讨论】:

      【解决方案2】:

      假设您使用 Webpack 进行测试,您可以使用 Sokra(Webpack 的创建者)的 null-loader,以确保所有 SCSS 要求/导入结果为 null,从而不会导致任何错误。

       {test: /\.scss?$/, loader: 'null'}
      

      https://github.com/webpack/null-loader

      【讨论】:

      • 我正在使用 webpack,但仅用于在有 karma 的客户端站点上进行测试,所以这会起作用。但我有“通用”应用程序和测试我从命令行运行的服务器,如上所述。
      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 2020-06-23
      • 1970-01-01
      相关资源
      最近更新 更多