Open History to see the last commit
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 provideExperimentalZonelessChangeDetection,
19 runInInjectionContext,
20} from '@angular/core'
21import { TestBed } from '@angular/core/testing'
22import { assertInjector } from './assert-injector'
23β
24describe('assertInjector', () => {
25 const token = new InjectionToken('token', {
26 factory: () => 1,
27 })
28β
29 function injectDummy(injector?: Injector) {
30 injector = assertInjector(injectDummy, injector)
31 return runInInjectionContext(injector, () => inject(token))
32 }
33β
34 function injectDummyTwo(injector?: Injector) {
35 return assertInjector(injectDummyTwo, injector, () => inject(token) + 1)
36 }
37β
38 it('given no custom injector, when run in injection context, then return value', () => {
39 TestBed.configureTestingModule({
40 providers: [provideExperimentalZonelessChangeDetection()],
41 })
42 TestBed.runInInjectionContext(() => {
43 const value = injectDummy()
44 const valueTwo = injectDummyTwo()
45 expect(value).toEqual(1)
46 expect(valueTwo).toEqual(2)
47 })
48 })
49β
50 it('given no custom injector, when run outside injection context, then throw', () => {
51 expect(() => injectDummy()).toThrowError(
52 /injectDummy\(\) can only be used within an injection context/i,
53 )
54 expect(() => injectDummyTwo()).toThrowError(
55 /injectDummyTwo\(\) can only be used within an injection context/i,
56 )
57 })
58β
59 it('given a custom injector, when run in that injector context without providing number, then throw', () => {
60 expect(() => injectDummy(Injector.create({ providers: [] }))).toThrowError(
61 /No provider for InjectionToken/i,
62 )
63 expect(() =>
64 injectDummyTwo(Injector.create({ providers: [] })),
65 ).toThrowError(/No provider for InjectionToken/i)
66 })
67β
68 it('given a custom injector, when run in that injector context and providing number, then return value', () => {
69 const value = injectDummy(
70 Injector.create({ providers: [{ provide: token, useValue: 2 }] }),
71 )
72 const valueTwo = injectDummyTwo(
73 Injector.create({ providers: [{ provide: token, useValue: 2 }] }),
74 )
75 expect(value).toEqual(2)
76 expect(valueTwo).toEqual(3)
77 })
78})