'How to write testcase for a method in a component that dispatches an action and calls an selector using Jasmine in Angular?
So I have made a component that takes input from parent component and emits an string[] output to its parent component. So within this component there is an method GetDataKey() which takes an string input and dispatches an action which updates the store with some values. And then an selector is called which sends only the string[] data from store and then we assign it to 'ResultData' variable. And after that we emit the 'ResultData' variable.
export interface OptionArrayinterface {
options: string[]
}
searchable-dropdown.component.ts
export class SearchableDropdownComponent implements OnInit, OnChanges {
@Input() searchKey! : string
@Output() searchResult = new EventEmitter()
constructor(private store : Store< { GetOptionsStore : OptionArrayinterface }>) { }
ngOnInit(): void {
this.GetDataKey(this.searchKey)
}
ngOnChanges(changes: SimpleChanges): void {
this.GetDataKey(this.searchKey)
}
ResultData : string[] = []
GetDataKey(SearchKey : string)
{
this.store.dispatch(GetOptionsKeyAction( { searchkey : SearchKey } ))
this.store.select(GetOptionsSelector).subscribe(
(res) => {
this.ResultData = res
}
)
this.searchResult.emit(this.ResultData)
}
}
searchable-dropdown.component.spec.ts
describe('SearchableDropdownComponent', () => {
let component: SearchableDropdownComponent;
let fixture: ComponentFixture<SearchableDropdownComponent>;
const initialState : OptionArrayinterface = {
options: [
"abc",
"xyz",
]
}
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [
provideMockStore( { initialState } )
],
declarations: [ SearchableDropdownComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SearchableDropdownComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('testing GetDataKey(SearchKey : string)', () => {
// let resultdata : string[] = []
// expect(component.ResultData).toEqual(resultdata)
})
});
So I was confused about how I should tackle writing testcases for 'GetDataKey()' method since within the method there is an action and an selector that is called.
Any help or advice would be appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
