I have a rather simple, working Angular 2 component. The component renders some div sibling elements based off of an array of values that I have sorted. This component implements OnChanges
. The sorting functionality happens during the execution of ngOnChanges()
. Initially, my @Input()
attribute references an array of values that are unsorted. Once the change detection kicks in, the resulting DOM elements are sorted as expected.
I have written a Karma unit test to verify that the sorting logic in the component has taken place and that the expected DOM elements are rendered in sorted order. I programmatically set the component property in the unit test. After calling fixture.detectChanges()
, the component renders its DOM. However, what I am ngOnChanges()` function, I see it is never executed. What is the correct way to unit test this behavior?
Here is my component:
@Component({
selector: 'field-value-map-item',
templateUrl: 'field-value-map-item.component.html',
styleUrls: [ 'field-value-map-item.component.less' ]
})
export class FieldValueMapItemComponent implements OnChanges {
@Input() data: FieldMapping
private mappings: { [id: number]: Array<ValueMapping> }
ngOnChanges(changes: any): void {
if (changes.data) { // && !changes.data.isFirstChange()) {
this.handleMappingDataChange(changes.data.currentValue)
}
}
private handleMappingDataChange(mapping: FieldMapping) {
// update mappings data structure
this.mappings = {};
if (mapping.inputFields) {
mapping.inputFields.forEach((field: Field) => {
field.allowedValues = sortBy(field.allowedValues, [ 'valueText' ])
})
}
if (mapping.valueMap) {
// console.log(mapping.valueMap.mappings.map((item) => item.input))
// order mappings by outputValue.valueText so that all target
// values are ordered.
let orderedMappings = sortBy(mapping.valueMap.mappings, [ 'inputValue.valueText' ])
orderedMappings.forEach((mapping) => {
if (!this.mappings[mapping.outputValue.id]) {
this.mappings[mapping.outputValue.id] = []
}
this.mappings[mapping.outputValue.id].push(mapping)
})
}
}
}
The component template:
<div class="field-value-map-item">
<div *ngIf="data && data.valueMap"
class="field-value-map-item__container">
<div class="field-value-map-item__source">
<avs-header-panel
*ngIf="data.valueMap['@type'] === 'static'"
[title]="data.inputFields[0].name">
<ol>
<li class="field-value-mapitem__value"
*ngFor="let value of data.inputFields[0].allowedValues">
{{value.valueText}}
</li>
</ol>
</avs-header-panel>
</div>
<div class="field-value-map-item__target">
<div *ngFor="let value of data.outputField.allowedValues">
<avs-header-panel [title]="value.valueText">
<div *ngIf="mappings && mappings[value.id]">
<div class="field-value-mapitem__mapped-value"
*ngFor="let mapping of mappings[value.id]">
{{mapping.inputValue.valueText}}
</div>
</div>
</avs-header-panel>
</div>
</div>
</div>
</div>
Here is my unit test:
describe('component: field-mapping/FieldValueMapItemComponent', () => {
let component: FieldValueMapItemComponent
let fixture: ComponentFixture<FieldValueMapItemComponent>
let de: DebugElement
let el: HTMLElement
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
FieldValueMapItemComponent
],
imports: [
CommonModule
],
providers: [ ],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
})
fixture = TestBed.createComponent(FieldValueMapItemComponent)
component = fixture.componentInstance
de = fixture.debugElement.query(By.css('div'))
el = de.nativeElement
})
afterEach(() => {
fixture.destroy()
})
describe('render DOM elements', () => {
beforeEach(() => {
spyOn(component, 'ngOnChanges').and.callThrough()
component.data = CONFIGURATION.fieldMappings[0]
fixture.detectChanges()
})
it('should call ngOnChanges', () => {
expect(component.ngOnChanges).toHaveBeenCalled() // this fails!
})
})
describe('sort output data values', () => {
beforeEach(() => {
component.data = CONFIGURATION.fieldMappings[1]
fixture.detectChanges()
})
it('should sort source field allowed values by their valueText property', () => {
let valueEls = el.querySelectorAll('.field-value-mapitem__value')
let valueText = map(valueEls, 'innerText')
expect(valueText.join(',')).toBe('Active,Foo,Terminated,Zip') // this fails
})
})
})
A solution to this problem is to introduce a simple Component
in the unit test. This Component
contains the component in question as a child. By setting input attributes on this child component, you will trigger the ngOnChanges()
function to be called just as it would in the application.
Updated unit test (notice the simple @Component({...}) class ParentComponent
at the top). In the applicable test cases, I instantiated a new test fixture and component (of type ParentComponent) and set the class attributes that are bound to the child components input attribute in order to trigger the ngOnChange()
.
@Component({
template: `
<div id="parent">
<field-value-map-item [data]="childData"></field-value-map-item>
</div>
`
})
class ParentComponent {
childData = CONFIGURATION.fieldMappings[1]
}
describe('component: field-mapping/FieldValueMapItemComponent', () => {
let component: FieldValueMapItemComponent
let fixture: ComponentFixture<FieldValueMapItemComponent>
let de: DebugElement
let el: HTMLElement
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
FieldValueMapItemComponent,
ParentComponent
],
imports: [
CommonModule
],
providers: [ ],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
})
fixture = TestBed.createComponent(FieldValueMapItemComponent)
component = fixture.componentInstance
de = fixture.debugElement.query(By.css('div'))
el = de.nativeElement
})
// ...
describe('sort output data values', () => {
let parentComponent: ParentComponent
let parentFixture: ComponentFixture<ParentComponent>
let parentDe: DebugElement
let parentEl: HTMLElement
beforeEach(() => {
parentFixture = TestBed.createComponent(ParentComponent)
parentComponent = parentFixture.componentInstance
parentDe = parentFixture.debugElement.query(By.css('#parent'))
parentEl = parentDe.nativeElement
parentFixture.detectChanges()
})
it('should sort source field allowed values by their valueText property', () => {
let valueEls = parentEl.querySelectorAll('.field-value-mapitem__value')
let valueText = map(valueEls, 'innerText')
expect(valueText.join(',')).toBe('Active,Foo,Terminated,Zip')
})
it('should sort target field mapped values by `inputValue.valueText`', () => {
parentComponent.childData = CONFIGURATION.fieldMappings[2]
parentFixture.detectChanges()
let valueEls = parentEl.querySelectorAll('.field-value-mapitem__mapped-value')
let valueText = map(valueEls, 'innerText')
expect(valueText.join(',')).toBe('BRC,FreeBurrito,FreeTaco')
})
})
})
The other way is calling ngOnChanges directly.
it('should render `Hello World!`', () => {
greeter.name = 'World';
//directly call ngOnChanges
greeter.ngOnChanges({
name: new SimpleChange(null, greeter.name)
});
fixture.detectChanges();
expect(element.querySelector('h1').innerText).toBe('Hello World!');
});
ref: https://medium.com/@christophkrautz/testing-ngonchanges-in-angular-components-bbb3b4650ee8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.