0

I'm trying to test a react component.

Foo.jsx

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

...rest of code

Foo.spec.js (this is just a boiler place for test)

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;

When trying to load mocha from CLI

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

And I'm getting an error

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

I tried: Handle WebPack CSS imports when testing with Mocha

but it doesn't work either.

If I comment that line out, the test is executing.

Community
  • 1
  • 1
DeBoer
  • 551
  • 1
  • 7
  • 16

2 Answers2

1

I've found the solution. https://github.com/darul75/web-react/blob/master/app/components/TodoSection/TodoItem.js#L13

When I'm running test on the server:

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

On the client I have to add a plugin to the webpack config:

plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      'APP_ENV': JSON.stringify('BROWSER'),
     }
  })
]
DeBoer
  • 551
  • 1
  • 7
  • 16
0

Assuming you're using Webpack for the test, you can use Sokra (the creator of Webpack)'s null-loader, to make sure that all SCSS requires/imports result in null, and thereby not causing any errors.

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

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

Thomas
  • 5,110
  • 1
  • 16
  • 17
  • I'm using webpack but only for test on the client site with karma, so this would work. But I have 'universal' app and tests for server I'm running from the command line like described above. – DeBoer Nov 27 '15 at 08:48