mirror of https://github.com/grafana/grafana
parent
5e240c49cb
commit
788ea5d624
@ -0,0 +1,33 @@ |
||||
import { HttpHandler } from 'msw'; |
||||
import { SetupWorker } from 'msw/browser'; |
||||
|
||||
import worker from './worker'; |
||||
|
||||
export type Scenario = HttpHandler[]; |
||||
|
||||
type ScenarioRegistryOptions = { |
||||
worker?: SetupWorker; // optionally use a worker that is different from the default one
|
||||
}; |
||||
|
||||
export class ScenarioRegistry { |
||||
scenarios: Map<string, Scenario>; |
||||
worker: SetupWorker; |
||||
|
||||
constructor(options?: ScenarioRegistryOptions) { |
||||
this.scenarios = new Map(); |
||||
this.worker = options?.worker ?? worker; |
||||
} |
||||
|
||||
registerScenario(name: string, scenario: Scenario) { |
||||
this.scenarios.set(name, scenario); |
||||
} |
||||
|
||||
// return an array of handlers from the registry of scenarios so we can pass this into the MSW worker
|
||||
handlers(): HttpHandler[] { |
||||
return Array.from(this.scenarios.values()).flat(); |
||||
} |
||||
|
||||
availableScenarios(): string[] { |
||||
return Array.from(this.scenarios.keys()); |
||||
} |
||||
} |
@ -1 +1,3 @@ |
||||
export {}; |
||||
import { setScenarioRegistryHook, useScenarioRegistry } from './useScenarioRegistry'; |
||||
|
||||
export { useScenarioRegistry, setScenarioRegistryHook }; |
||||
|
@ -0,0 +1,22 @@ |
||||
import { ScenarioRegistry } from './registry'; |
||||
|
||||
export type UseScenarioRegistryOptions = {}; |
||||
|
||||
export type UseScenarioRegistry = (options: UseScenarioRegistryOptions) => ScenarioRegistry; |
||||
|
||||
let singleton: UseScenarioRegistry | undefined; |
||||
|
||||
export function setScenarioRegistryHook(hook: UseScenarioRegistry): void { |
||||
// We allow overriding the hook in tests
|
||||
if (singleton && process.env.NODE_ENV !== 'test') { |
||||
throw new Error('setScenarioRegistryHook() function should only be called once, when Grafana is starting.'); |
||||
} |
||||
singleton = hook; |
||||
} |
||||
|
||||
export function useScenarioRegistry(options: UseScenarioRegistryOptions): ScenarioRegistry { |
||||
if (!singleton) { |
||||
throw new Error('setScenarioRegistryHook(options) can only be used after the Grafana instance has started.'); |
||||
} |
||||
return singleton(options); |
||||
} |
@ -0,0 +1,6 @@ |
||||
import { ScenarioRegistry } from '@grafana/test-utils'; |
||||
|
||||
export function useScenarioRegistry(): ScenarioRegistry { |
||||
const registry = new ScenarioRegistry(); |
||||
return registry; |
||||
} |
Loading…
Reference in new issue