Adding a Jest Setup File

Since this chapter’s project will have three components (Carousel, CarouselButton, and CarouselSlide), it’s going to have three test files. Rather than duplicate the Enzyme configuration logic across all three, we should move that logic into a “setup file” that will only run once whenever Jest runs our tests.

Actually, we’re going to need two files: the setup file, and a Jest configuration to point to it. Let’s start with the configuration. By default, Jest looks for a file called jest.config.js in the root of the project:

 module.exports = {
setupTestFrameworkScriptFile: ​'./src/tests/jestSetup.js'​,
 };

The setupTestFrameworkScriptFile entry tells Jest to go ahead and “Run the file called src/tests/jestSetup.js in the root of this project before running any tests.”

Jest supports many other configuration options, but we won’t be needing them. If you’re curious, consult the official docs.[44]

Now let’s create that file:

 import​ Adapter ​from​ ​'enzyme-adapter-react-16'​;
 import​ { configure } ​from​ ​'enzyme'​;
 
 configure({ adapter: ​new​ Adapter() });

If you’re running Wallaby or jest --watchAll, you’ll need to restart it in order for Jest to recognize the new setup.

With the Jest setup file in place, you no longer need to run Enzyme’s configure() method in each individual test file:

 import​ React ​from​ ​'react'​;
»import​ { shallow } ​from​ ​'enzyme'​;
 import​ CarouselButton ​from​ ​'../CarouselButton'​;
 
 describe(​'CarouselButton'​, () => {
 const​ text = ​'Button text'​;
 let​ wrapper;
 
  beforeEach(() => {
  wrapper = shallow(<CarouselButton>​{​text​}​</CarouselButton>);
  });
 
  it(​'renders a <button>'​, () => {
  expect(wrapper.type()).toBe(​'button'​);
  });
 
  it(​'passes `children` through to the <button>'​, () => {
  expect(wrapper.prop(​'children'​)).toBe(text);
  });
 
  it(​'passes other props through to the <button>'​, () => {
 const​ onClick = () => {};
 const​ className = ​'my-carousel-button'​;
 const​ dataAction = ​'prev'​;
  wrapper.setProps({ onClick, className, ​'data-action'​: dataAction });
  expect(wrapper.prop(​'onClick'​)).toBe(onClick);
  expect(wrapper.prop(​'className'​)).toBe(className);
  expect(wrapper.prop(​'data-action'​)).toBe(dataAction);
  });
 });

Commit your improved testing setup:

 :wrench: Add Jest setup file

With that in place, it’s time to build CarouselButton’s sibling, CarouselSlide.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.103.202