jeudi 20 août 2015

Jasmine Tests give error "Uncaught ReferenceError: require is not defined"

I am trying to run Jasmine tests with Karma on my React site. My tests were working before, and I'm not sure what has changed, but now I get the error:

Uncaught ReferenceError: require is not defined

for Chrome and PhantomJS and Firefox give me similar errors. Please let me know if more info would be helpful. I have found a lot of similar questions on the web, but nothing that fixes the problem.

You can see the test file below and the full project is on my github repo.

Thanks in advance!

My test file looks like this:

var React = require('react/addons');
var Story = require('../../app/js/components/story.jsx');
var TestUtils = React.addons.TestUtils;
var testUtilsAdditions = require('react-testutils-additions');

  describe('Story component', function () {
    var component;

    beforeEach(function () {
      var element = React.createElement(Story);
      element.props.data = {
        storyTitle: 'front end test title',
        author : 'front end author',
        storyText : 'front end story text'
      };
      component = TestUtils.renderIntoDocument(element);
      });

    it('should display a story', function () {
      expect(component.props.data).toBeDefined();
      expect(component.props.data.storyTitle).toBeDefined();
      expect(component.props.data.storyTitle).toBe('front end test title');
      expect(component.props.data.author).toBe('front end author');
      expect(component.props.data.storyText).toBe('front end story text');
    });

  });

3 commentaires:

  1. Hey you are right. so many similar issues but no solution matching to your problem. Here I am providing one solution.
    npm install browserify --save
    npm install karma-browserify --save-dev

    then in karma.conf.js
    frameworks: ['browserify', 'jasmine'] //make sure browserify comes first
    ........
    plugins: [
    'karma-browserify',
    ...............
    ]

    RépondreSupprimer
  2. one more change i missed to tell to change in karma.conf.js
    preprocessors: {
    ..................
    'xx/scripts/**/*.spec.js': ['browserify']
    }

    RépondreSupprimer
  3. ANOTHER alternative solution for COMMONJS is...
    Replace the word 'browserify' in above solution with 'commonjs'. all steps remains same.

    RépondreSupprimer