JSHint thinks Jasmine functions are undefined

2019-02-04 02:14发布

问题:

I've got a Grunt setup which uses Karma+Jasmine and JSHint. Whenever I run JSHint on my spec file, I get a series of "undefined" errors, most of which are for Jasmine's built-in functions. For example:

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.

(I also get some undefined errors for the variables and functions from the JS file that my spec is meant to test against, but I'm not sure why that is and it may be a separate issue.)

My Karma config file has frameworks: [ "jasmine" ] in it, I don't have any globals set for JSHint, and I don't have a .jshintrc file since I'm configuring it in Grunt. I did try adding Jasmine's functions as JSHint globals in my Gruntfile at one point, but setting them as either true or false didn't make a difference—the errors still persisted when JSHint ran.

What am I missing? I can't seem to do anything to get JSHint to skip definition checking for Jasmine's functions in my spec file.

回答1:

You can just add "jasmine": true to your .jshintrc file.



回答2:

MINOR CORRECTION - there should be "" around predef in the .jshintrc file.

Fixed by adding this to the jshint options in my Gruntfile.coffee:

predef: [
    "jasmine"
    "describe"
    "xdescribe"
    "before"
    "beforeEach"
    "after"
    "afterEach"
    "it"
    "xit"
    "it"
    "inject"
    "expect"
    "spyOn"
]

.jshintrc:

"predef": [
    "jasmine",
    "describe",
    "xdescribe",
    "before",
    "beforeEach",
    "after",
    "afterEach",
    "it",
    "xit",
    "it",
    "inject",
    "expect",
    "spyOn",
]


回答3:

I fixed this in Gruntfile.js adding jasmine: true to the options of the jshint task:

jshint:
{
    options:
    {
        ...
        node: true,
        jasmine: true,
        ...
    },
    ...
},

Like the OP, I'm not using a .jshintrc file either.



回答4:

I believe the other answers are correct, but I have never seen such exception before, however I see it now. Then I noticed that my tests are not in IIFE. So I moved them in IIFE like this and I no longer get such JSHINT warnings.

(function () {

  describe('foo', () => {
     it('bar', () => {
        expect(1+1).toEqual(2);
     });
  });

})();