Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Skye Aoki
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
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,777 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
216,165 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
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.