MikeW
MikeW

Reputation: 1620

TypeError: undefined not a constructor when using beforeEach in jasmine test

I have run into a problem when writing unit tests in jasmine which I have managed to distill down to a a very basic test scenario:

describe('weird shit', function () {
    var myVal;
    beforeEach(myVal = 0);
    it('throws for some reason', function () {
        expect(myVal).toBe(0);
    });
});

and this throws a TypeError:

Test 'weird shit:throws for some reason' failed
    TypeError: undefined is not a constructor (evaluating 'queueableFn.fn.call(self.userContext)') in 

file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js (line 1886)
    run@file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js:1874:20
    execute@file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js:1859:13
    queueRunnerFactory@file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js:697:42
    execute@file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js:359:28
    fn@file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js:2479:44

if I removed the beforeEach then it works fine:

describe('weird shit', function () {
    var myVal =0;
    it('throws for some reason', function () {
        expect(myVal).toBe(0);
    });
});

Which I do not understand, the beforeEach is very basic, please help.

Upvotes: 0

Views: 538

Answers (3)

willow
willow

Reputation: 33

Purpose of beforeEach() is to execute some function that contains code to setup your specs.

In this case, it is setting variable myVal = 0

You should pass a function to beforeEach() like below:

beforeEach(function() {
  myVal = 0
});

in order to successfully setup your variable.

Upvotes: 0

Gray Fox
Gray Fox

Reputation: 357

beforeEach(function(){myVal = 0;});

Upvotes: 0

Phani Rahul Sivalenka
Phani Rahul Sivalenka

Reputation: 150

beforeEach accepts a function, you passed the result of myVal = 0, which is 0, which isn't a function.

beforeEach(myVal = 0);

Replace the above code with the following:

beforeEach(function() {
  myVal = 0;
});

Refer the documentation of jasmine 2.5 here for more information.

Upvotes: 3

Related Questions