|
1 | | -import { Component, NgModule } from '@angular/core'; |
| 1 | +import { Component, NgModule, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; |
2 | 2 | import { NoopAnimationsModule, BrowserAnimationsModule } from '@angular/platform-browser/animations'; |
3 | 3 | import { TestBed } from '@angular/core/testing'; |
4 | 4 | import { render } from '../src/public_api'; |
@@ -71,3 +71,47 @@ describe('animationModule', () => { |
71 | 71 | expect(() => TestBed.inject(NoopAnimationsModule)).toThrow(); |
72 | 72 | }); |
73 | 73 | }); |
| 74 | + |
| 75 | +@Component({ |
| 76 | + selector: 'fixture', |
| 77 | + template: ` {{ name }} `, |
| 78 | +}) |
| 79 | +class FixtureWithNgOnChangesComponent implements OnInit, OnChanges { |
| 80 | + @Input() name = 'Sarah'; |
| 81 | + @Input() nameInitialized?: (name: string) => void; |
| 82 | + @Input() nameChanged?: (name: string, isFirstChange: boolean) => void; |
| 83 | + |
| 84 | + ngOnInit() { |
| 85 | + if (this.nameInitialized) { |
| 86 | + this.nameInitialized(this.name); |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + ngOnChanges(changes: SimpleChanges) { |
| 91 | + if (changes.name && this.nameChanged) { |
| 92 | + this.nameChanged(changes.name.currentValue, changes.name.isFirstChange()); |
| 93 | + } |
| 94 | + } |
| 95 | +} |
| 96 | +describe('Angular component life-cycle hooks', () => { |
| 97 | + test('will call ngOnInit on initial render', async () => { |
| 98 | + const nameInitialized = jest.fn(); |
| 99 | + const componentProperties = { nameInitialized }; |
| 100 | + const component = await render(FixtureWithNgOnChangesComponent, { componentProperties }); |
| 101 | + |
| 102 | + component.getByText('Sarah'); |
| 103 | + expect(nameInitialized).toBeCalledWith('Sarah'); |
| 104 | + }); |
| 105 | + |
| 106 | + test('will call ngOnChanges on initial render before ngOnInit', async () => { |
| 107 | + const nameInitialized = jest.fn(); |
| 108 | + const nameChanged = jest.fn(); |
| 109 | + const componentProperties = { nameInitialized, nameChanged }; |
| 110 | + const component = await render(FixtureWithNgOnChangesComponent, { componentProperties }); |
| 111 | + |
| 112 | + component.getByText('Sarah'); |
| 113 | + expect(nameChanged).toBeCalledWith('Sarah', true); |
| 114 | + // expect `nameChanged` to be called before `nameInitialized` |
| 115 | + expect(nameChanged.mock.invocationCallOrder[0]).toBeLessThan(nameInitialized.mock.invocationCallOrder[0]); |
| 116 | + }); |
| 117 | +}); |
0 commit comments