11import type { JSONSchemaForNPMPackageJsonFiles } from '@schemastore/package' ;
2+ import type { RuleContext } from '@typescript-eslint/utils/ts-eslint' ;
3+
4+ interface ContextSettings {
5+ [ key : string ] : unknown ;
6+ jest ?: EslintPluginJestSettings ;
7+ }
8+
9+ interface EslintPluginJestSettings {
10+ version : JestVersion | string ;
11+ }
12+
13+ export interface EslintPluginJestRuleContext
14+ extends Readonly < RuleContext < never , [ ] > > {
15+ settings : ContextSettings ;
16+ }
217
318export type JestVersion =
419 | 14
@@ -22,7 +37,25 @@ export type JestVersion =
2237
2338let cachedJestVersion : JestVersion | null = null ;
2439
25- export const detectJestVersion = ( ) : JestVersion => {
40+ const parseJestVersion = ( rawVersion : number | string ) : JestVersion => {
41+ if ( typeof rawVersion === 'number' ) {
42+ return rawVersion ;
43+ }
44+
45+ const [ majorVersion ] = rawVersion . split ( '.' ) ;
46+
47+ return parseInt ( majorVersion , 10 ) ;
48+ } ;
49+
50+ export const getContextJestVersion = (
51+ context : EslintPluginJestRuleContext ,
52+ ) : JestVersion | null => {
53+ return context . settings . jest ?. version
54+ ? parseJestVersion ( context . settings . jest . version )
55+ : null ;
56+ } ;
57+
58+ export const detectJestVersion = ( ) : JestVersion | null => {
2659 if ( cachedJestVersion ) {
2760 return cachedJestVersion ;
2861 }
@@ -35,13 +68,15 @@ export const detectJestVersion = (): JestVersion => {
3568 require ( jestPath ) as JSONSchemaForNPMPackageJsonFiles ;
3669
3770 if ( jestPackageJson . version ) {
38- const [ majorVersion ] = jestPackageJson . version . split ( '.' ) ;
39-
40- return ( cachedJestVersion = parseInt ( majorVersion , 10 ) ) ;
71+ return ( cachedJestVersion = parseJestVersion ( jestPackageJson . version ) ) ;
4172 }
4273 } catch { }
4374
44- throw new Error (
45- 'Unable to detect Jest version - please ensure jest package is installed, or otherwise set version explicitly' ,
46- ) ;
75+ return null ;
76+ } ;
77+
78+ export const getJestVersion = (
79+ context : EslintPluginJestRuleContext ,
80+ ) : JestVersion | null => {
81+ return getContextJestVersion ( context ) || detectJestVersion ( ) ;
4782} ;
0 commit comments