Reputation: 2936
I'm using VS Code in a Typescript project that uses Jest for testing. For some reason, VS Code thinks that the Jest globals are not available:
I have the Jest typedefs installed in my dev dependencies.
"devDependencies": {
// ...truncated
"@types/jest": "^20",
"jest": "^20.0.4",
"ts-jest": "^20.0.7",
"ts-node": "^5.0.0",
"typescript": "~2.4.0"
}
Upvotes: 6
Views: 7657
Reputation: 837
Update: As of Jest 26, the @jest/globals
package can be used to explicitly import
Jest functions instead of relying on globals:
import { describe, it, expect } from '@jest/globals'
By explicitly importing, you ensure that these variables are available in your test file.
Jest 26.5 further added the injectGlobals
config that you can set to false
to disable globals in your test files:
// jest.config.js
/** @type {import('jest').Config} */
const config = {
injectGlobals: false,
};
module.exports = config;
For versions of Jest older than 26, you can use the jest-without-globals
package as described below:
I've similarly struggled with this problem a number of times despite having @types/jest
in my devDependencies
too.
I created jest-without-globals
as a very tiny wrapper to support importing Jest's features instead of relying on globals, thereby ensuring the variables exist.
It's written in TypeScript as well, ensuring that it's typed properly when imported and that you don't need to do anything other than an import to make the types function.
Per the Usage docs, it's straightforward to use:
import { describe, it, expect } from 'jest-without-globals' describe('describe should create a section', () => { it('it should checkmark', () => { expect('').toBe('') }) })
All of the functions available in Jest's API, as well as
jest
andexpect
, can be imported fromjest-without-globals
.
Upvotes: 3
Reputation: 388
Correct answer here is that typescript requires type declarations for jest before jest global objects are visible for intellisense.
Add this triple-slash directive to beginning of your test file:
/// <reference types="jest" />
Upvotes: 11
Reputation: 2936
I upgraded my version of Typescript to 2.8 and this problem went away. I'm going to assume it was some sort of cache issue.
Upvotes: 1