TypeError:在jasmine测试中使用beforeEach时,undefined不是构造函数

时间:2016-11-21 13:07:55

标签: javascript unit-testing jasmine

我在jasmine编写单元测试时遇到了一个问题,我已经设法将其提炼为一个非常基本的测试场景:

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

并抛出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

如果我删除beforeEach,那么它可以正常工作:

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

我不明白,beforeEach非常基本,请帮助。

3 个答案:

答案 0 :(得分:3)

beforeEach接受一个函数,您传递了myVal = 0的结果,0,这不是函数。

beforeEach(myVal = 0);

用以下内容替换上述代码:

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

有关详细信息,请参阅jasmine 2.5 here的文档。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

beforeEach()的目的是执行一些包含用于设置规格的代码的函数。

在这种情况下,它正在设置变量myVal = 0

您应将函数传递给beforeEach(),如下所示:

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

为了成功设置变量。