Search code examples
reactjsunit-testingwebpackrequirejsjestjs

JEST Should I run test cases on src or lib?


I have a Jest test suite that fails to run because the component it's trying to test depends on a RequireJS module. Here's the error I'm seeing:

FAIL tests/components/MyComponent.test.js ● Test suite failed to run

ReferenceError: define is not defined

  at Object.<anonymous> (node_modules/private-npm-module/utils.js:1:90)

However if I run my test cases on source folder that is written in ES6, it runs fine since it does not have the AMD of requirejs. I am confused if it is the right practice to run test case on source code or should we run it on lib(built) code?


Solution

  • Generally you want to test the source code, rather than built code.

    If you refer to Jest's React tutorial, it generally suggests you import your components rather than testing the built bundle file.

    Example:

    import React from 'react';
    import {shallow} from 'enzyme';
    import CheckboxWithLabel from '../CheckboxWithLabel';
    
    test('CheckboxWithLabel changes the text after click', () => {
      // Render a checkbox with label in the document
      const checkbox = shallow(<CheckboxWithLabel labelOn="On" labelOff="Off" />);
    
      expect(checkbox.text()).toEqual('Off');
    
      checkbox.find('input').simulate('change');
    
      expect(checkbox.text()).toEqual('On');
    });
    

    Source: https://facebook.github.io/jest/docs/en/tutorial-react.html