JavaScript JavaScript Unit Testing Improving Our Tests Making Tests Easier with Fixtures: Setup

Skye Aoki
Skye Aoki
Full Stack JavaScript Techdegree Graduate 28,347 Points

Is before() just for semantic benefit? Why not just set up the player var before the specs w/o wrapping it in before()?

I understand how beforeEach() can be useful but what does before() really do for you? In this example, you can take away the before and simply define the player variable above the specs and they will still have access to it and the test passes.

3 Answers

Gabbie Metheny
Gabbie Metheny
33,703 Points

Guil doesn't go into it in detail, but in the next video he talks about teardown using after and afterEach. These methods can be used to clean up after your tests run. That's not needed in this project, but he's probably introducing it as a best practice since a more complicated project might involve interacting with the DOM or modifying a pretend database.

Philip Enchin
seal-mask
.a{fill-rule:evenodd;}techdegree
Philip Enchin
Full Stack JavaScript Techdegree Student 24,714 Points

I was wondering the same thing, actually. I found a good, detailed answer on Stack Overflow which reminded me of trouble I had using Jasmine some time ago.

The big reason (in my eyes) is that because all tests are placed in callbacks, by using before(), you'll allow the testing framework to make sure things run at the right time. Perhaps not as important for before() in every case, but critical for other hooks.

Steven Parker
Steven Parker
207,988 Points

It may make no difference to the running of the test, but if you're establishing conditions specifically for the test it would make sense to set them up in a "before" rather than outside of the test code.

I haven't tried it, but I suspect it would also prevent anything from being added to the global namespace.

Skye Aoki
Skye Aoki
Full Stack JavaScript Techdegree Graduate 28,347 Points

I meant name the var within the describe() function. It's still contained within the same unit test. The only difference is it's not wrapped in before.