Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

assert-injector.test.ts

74 lines2.4 KB

1/* eslint-disable @cspell/spellchecker */
2/**
3 * The code in this file is adapted from NG Extension Platform at https://ngxtension.netlify.app.
4 *
5 * Original Author: Chau Tran
6 *
7 * NG Extension Platform is an open-source project licensed under the MIT license.
8 *
9 * For more information about the original code, see
10 * https://github.com/nartc/ngxtension-platform
11 */
12/* eslint-enable */
13​
14import {
15 InjectionToken,
16 Injector,
17 inject,
18 runInInjectionContext,
19} from '@angular/core'
20import { TestBed } from '@angular/core/testing'
21import { assertInjector } from './assert-injector'
22​
23describe(assertInjector.name, () => {
24 const token = new InjectionToken('token', {
25 factory: () => 1,
26 })
27​
28 function injectDummy(injector?: Injector) {
29 injector = assertInjector(injectDummy, injector)
30 return runInInjectionContext(injector, () => inject(token))
31 }
32​
33 function injectDummyTwo(injector?: Injector) {
34 return assertInjector(injectDummyTwo, injector, () => inject(token) + 1)
35 }
36​
37 it('given no custom injector, when run in injection context, then return value', () => {
38 TestBed.runInInjectionContext(() => {
39 const value = injectDummy()
40 const valueTwo = injectDummyTwo()
41 expect(value).toEqual(1)
42 expect(valueTwo).toEqual(2)
43 })
44 })
45​
46 it('given no custom injector, when run outside injection context, then throw', () => {
47 expect(() => injectDummy()).toThrowError(
48 /injectDummy\(\) can only be used within an injection context/i,
49 )
50 expect(() => injectDummyTwo()).toThrowError(
51 /injectDummyTwo\(\) can only be used within an injection context/i,
52 )
53 })
54​
55 it('given a custom injector, when run in that injector context without providing number, then throw', () => {
56 expect(() => injectDummy(Injector.create({ providers: [] }))).toThrowError(
57 /No provider for InjectionToken/i,
58 )
59 expect(() =>
60 injectDummyTwo(Injector.create({ providers: [] })),
61 ).toThrowError(/No provider for InjectionToken/i)
62 })
63​
64 it('given a custom injector, when run in that injector context and providing number, then return value', () => {
65 const value = injectDummy(
66 Injector.create({ providers: [{ provide: token, useValue: 2 }] }),
67 )
68 const valueTwo = injectDummyTwo(
69 Injector.create({ providers: [{ provide: token, useValue: 2 }] }),
70 )
71 expect(value).toEqual(2)
72 expect(valueTwo).toEqual(3)
73 })
74})