Skip to content

[Feature]: Add it modifier for run test inside injection context #3063

Open
@MillerSvt

Description

@MillerSvt

🚀 Feature Proposal

Currently if we need run many tests inside injection context, we should wrap each test in TestBed.runInInjectionContext function. It works, but not useful.

I propose to create it.injectable modifier to run tests inside injection context.

It can be opt in if needed.

Motivation

jest-preset-angular is useful tool for testing angular projects. If we create possibility to cre

Possible solution

declare global {
	namespace jest {
		interface It {
			injectable: (
				name: string,
				fn: (() => void) | (() => PromiseLike<unknown>),
				timeout?: number,
			) => void;
		}
	}
}

it.injectable = (
	name: string,
	fn: (() => void) | (() => PromiseLike<unknown>),
	timeout?: number,
) => {
	it(name, () => TestBed.runInInjectionContext(fn), timeout);
};

it.only.injectable = (
	name: string,
	fn: (() => void) | (() => PromiseLike<unknown>),
	timeout?: number,
) => {
	it.only(name, () => TestBed.runInInjectionContext(fn), timeout);
};

it.skip.injectable = (
	name: string,
	fn: (() => void) | (() => PromiseLike<unknown>),
	timeout?: number,
) => {
	it.skip(name, () => TestBed.runInInjectionContext(fn), timeout);
};

it.concurrent.injectable = (
	name: string,
	fn: (() => void) | (() => PromiseLike<unknown>),
	timeout?: number,
) => {
	it.concurrent(name, () => TestBed.runInInjectionContext(fn), timeout);
};

it.concurrent.only.injectable = (
	name: string,
	fn: (() => void) | (() => PromiseLike<unknown>),
	timeout?: number,
) => {
	it.concurrent.only(name, () => TestBed.runInInjectionContext(fn), timeout);
};

it.concurrent.skip.injectable = (
	name: string,
	fn: (() => void) | (() => PromiseLike<unknown>),
	timeout?: number,
) => {
	it.concurrent.skip(name, () => TestBed.runInInjectionContext(fn), timeout);
};

Usage

it.injectable('should be correct value', () => {
	const value = inject(VALUE_TOKEN);

	expect(value).toEqual(testValue);
});

Real world example: ngxtension/ngxtension-platform#593

Additional

I can create pr with that

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions