Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global `beforeEach` in jasmine?

I'm using Jasmine to write tests.

I have several test files, each file has a beforeEach, but they are exactly the same.

How do I provide a global beforeEach for them?

like image 552
Freewind Avatar asked May 12 '12 03:05

Freewind


People also ask

What is beforeEach in Jasmine?

JasmineJS - beforeEach() Advertisements. Another notable feature of Jasmine is before and after each function. Using these two functionalities, we can execute some pieces of code before and after execution of each spec. This functionality is very useful for running the common code in the application.

What is Xdescribe in Jasmine?

xdescribe: FunctionLike describe , but instructs the test runner to exclude this group of test cases from execution. This is useful for debugging, or for excluding broken tests until they can be fixed. See http://jasmine.github.io/ for more details.

What is beforeEach in JS?

before() is run once before all the tests in a describe. after() is run once after all the tests in a describe. beforeEach() is run before each test in a describe. afterEach() is run after each test in a describe. Which one you want to use depends on your actual test.

Which function is called before each test specification is run?

The beforeAll function is called only once before all the specs in describe are run, and the afterAll function is called after all specs finish. These functions can be used to speed up test suites with expensive setup and teardown. However, be careful using beforeAll and afterAll!


2 Answers

x1a4's answer confused me. This may be more clear:

When you declare a beforeEach function outside all describe blocks, it will trigger before each test (so before each it). It does not matter if you declare the beforeEach before or after your describe blocks.

You can include this in any specfile included in your test run—including in a file all on its own, hence the concept of a spec helper file that might contain just your global beforeEach declaration.

It's not mentioned in the documentation.

// Example:   beforeEach(function() {     localStorage.clear(); });  describe('My tests', function() {     describe('Test localstorage', function() {          it('Adds an item to localStorage', function() {             localStorage.setItem('foo', 'bar');             expect(localStorage.getItem('foo')).toBe('bar');         });          it('Is now empty because our beforeEach cleared localStorage', function() {             expect(localStorage.getItem('foo')).toBe(null);         });      }); }); 
like image 82
Blaise Avatar answered Sep 16 '22 18:09

Blaise


You can put it in your spec_helper.js file and it should work fine.

like image 21
x1a4 Avatar answered Sep 16 '22 18:09

x1a4