JSHint认为Jasmine函数未定义

Ian*_*28K 29 javascript jasmine jshint gruntjs karma-runner

我有一个使用Karma + Jasmine和JSHint的Grunt设置.每当我在我的spec文件上运行JSHint时,我都会遇到一系列"未定义"的错误,其中大部分是Jasmine的内置函数.例如:

Running "jshint:test" (jshint) task

   js/main.spec.js
      3 |describe("loadMatrix()", function() {
         ^ 'describe' is not defined.
      4 |    it("should not assign a value if no arg is passed.", function() {
             ^ 'it' is not defined.
Run Code Online (Sandbox Code Playgroud)

(我也从我的规范要测试的JS文件中得到一些未定义的变量和函数错误,但我不确定为什么会这样,它可能是一个单独的问题.)

我的Karma配置文件包含frameworks: [ "jasmine" ]在其中,我没有为JSHint设置任何全局变量,.jshintrc因为我在Grunt中配置它,所以我没有文件.我确实尝试在我的Gruntfile中将Jasmine的函数添加为JSHint全局变量,但是将它们设置为true或者false没有区别 - 当JSHint运行时,错误仍然存​​在.

我错过了什么?我似乎无法做任何让JSHint在我的spec文件中跳过Jasmine函数的定义检查.

Leo*_*tov 68

您只需添加"jasmine": true到您的.jshintrc文件即可.


Ian*_*28K 22

MINOR CORRECTION - .jshintrc文件中的predef周围应该有"".

通过将此添加到jshint我的选项中修复Gruntfile.coffee:

predef: [
    "jasmine"
    "describe"
    "xdescribe"
    "before"
    "beforeEach"
    "after"
    "afterEach"
    "it"
    "xit"
    "it"
    "inject"
    "expect"
    "spyOn"
]
Run Code Online (Sandbox Code Playgroud)

.jshintrc:

"predef": [
    "jasmine",
    "describe",
    "xdescribe",
    "before",
    "beforeEach",
    "after",
    "afterEach",
    "it",
    "xit",
    "it",
    "inject",
    "expect",
    "spyOn",
]
Run Code Online (Sandbox Code Playgroud)

  • [Leon的答案](http://stackoverflow.com/a/27136840/3116322)应该是公认的答案,因为仅定义““ jasmine”:true“要短得多。 (2认同)

GOT*_*O 0 10

我在Gruntfile.js中修复了这个问题,添加jasmine: true了jshint任务的选项:

jshint:
{
    options:
    {
        ...
        node: true,
        jasmine: true,
        ...
    },
    ...
},
Run Code Online (Sandbox Code Playgroud)

和OP一样,我也没有使用.jshintrc文件.