简体   繁体   中英

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 aa 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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM