Reputation: 77
I'm learning how to write tests for my code and my instructor explained to put the component being rendered in a beforeEach() function like this...
describe('CommentBox', () => {
let component;
beforeEach(() => {
component = renderComponent(CommentBox);
});
it('has the correct class', () => {
expect(component).to.have.class('comment-box');
});
it('has a text area', () => {
expect(component.find('textarea')).to.exist;
});
it('has a button', () => {
expect(component.find('button')).to.exist;
});
});
Why use beforeEach(). Why not just declare the component variable at the top of the describe function like so...
describe('CommentBox', () => {
const component = renderComponent(CommentBox);
it('has the correct class', () => {
expect(component).to.have.class('comment-box');
});
it('has a text area', () => {
expect(component.find('textarea')).to.exist;
});
it('has a button', () => {
expect(component.find('button')).to.exist;
});
});
This would seem to save a couple extra lines of code, and one less function you would have to write?
Upvotes: 0
Views: 264
Reputation: 307
The beforeEach
runs before each test. This means that each test gets fresh data to test with.
If you do it the other way each test could modify the object and then taint the object for the next test.
Its good practice to not create dependencies between tests so that you can more accurately find bugs or ensure your test actually tests the logic you intended.
I assume that your testing renderComponent
.
Upvotes: 1