Currently, I am testing a function that involves returning a promise and subsequently calling the same function again at a second level. However, I am facing difficulties in accessing this second level of call.
Below is the function code:
itemToForm = () => {
this.api.send(this.component, 'get', { lang: 'ES', filter: { id: this.item['id'] } }).then(resEsp => {
this.item = resEsp['data'][0];
this.api.send(this.component, 'get', { lang: 'EN', filter: { id: this.item['id'] } }).then(res => {
let itemEng = res['data'][0];
let fields = this.formDef
.map(register => register
.filter(field => field['register_table'].indexOf('traduction') !== -1)
.map(field => field['field_name'])
).filter(register => register.length);
fields = fields.length ? fields[0] : [];
if (itemEng)
this.item = Object.keys(itemEng)
.reduce((obj, key) => {
obj[key] = this.item[key];
if (fields.indexOf(key) !== -1) {
obj[key + '_eng'] = itemEng[key];
}
return obj
}, {});
if (this.item) {
this.setForm();
}
});
});
}
Although I have successfully tested the first level of the function, I am struggling with setting up the spyOn mock for the second level call.
Here is my test scenario:
describe('itemToForm()', () => {
it('should call api.send with resEsp', () => {
let item = { id: 1, name: 'test' };
component.component = 'Events';
let resEsp = {
data: [
{ id: 1, name: 'test1' },
{ id: 2, name: 'test2' },
{ id: 3, name: 'test3' }
]
};
component.item = item;
//let spy1 = spyOn(api, 'send').and.returnValue(Promise.resolve(resEsp));
let spy1 = spyOn(api, 'send').and.returnValue(Promise.resolve(resEsp));
component.itemToForm();
expect(spy1).toHaveBeenCalled();
expect(spy1).toHaveBeenCalledTimes(1);
expect(spy1).toHaveBeenCalledWith('Events', 'get', { lang: 'ES', filter: { id: 1 } });
});
it('should call api.send with res Eng', () => {
let itemEng = { id: 1, name: 'test', lang: 'EN' };
component.component = 'Events';
let resEsp = {data: [{ id: 1, name: 'test1' }, { id: 2, name: 'test2' }, { id: 3, name: 'test3' }]};
let res = {data: [{ id: 1, name: 'test1' }, { id: 2, name: 'test2' }, { id: 3, name: 'test3' }]};
component.item = itemEng;
//let spy1 = spyOn(api, 'send').and.returnValue(Promise.resolve(resEsp));
let spy1 = spyOn(api, 'send').and.returnValue(Promise.resolve(resEsp)).and.returnValue(Promise.resolve(res));
component.itemToForm();
expect(spy1).toHaveBeenCalled();
});
});