简体   繁体   中英

How to define once a component in Jest and Enzyme?

I'm using jest and enzyme to handle test cases in my application. For example I've an App component and I want to write 2 case tests for that:

 describe('App Component', () => { test('Render without error', () => { const wrapper = shallow(<App />); }); test('Check title tag', () => { const wrapper = shallow(<App />); const title = wrapper.find('h1'); expect(title.text()).toBe('App'); }); });

In above code, I've written twice const wrapper = shallow(<App />); to define component.

So, Is there any trick to define the wrapper once and use that more?

Or, That's correct and hasn't any performance issue?

I'd like to learn best practices actually!

Thanks

Your approach it's correct since each test needs to shallow the component and check some stuff. There are any performance issues here, If you want a tip, try to think a bit more about the test titles. i:e:

Render without error could be it renders

Check title tag could be title tag is equal to "App"

In this case can be:

  let wrapper;

  beforeEach(() => {
    wrapper = shallow(<App />);
  });
  ...

This won't work for tests that need to instantiate a component with different props, or do something before it's instantiated, then wrapper assignment needs to be moved to tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM