I am learning Angular unit test for chained promise . Here is code snippet and failed at expectation with error message Expected '' to equal 'bar'. What is needed to make it success ? I have used Angular 17 and Jasmine.I have tried with fakeAsync with tick & flush .
it(`nested promise testing`, fakeAsync(() =\> {
let item = '';
const mockItem = {
promise: Promise.resolve(new Response(JSON.stringify({ foo: 'bar' }))),
};
Promise.resolve(mockItem.promise)
.then((response) =\> response.json())
.then((data) =\> {
console.log('data = ' + data.foo);
item = data.foo;
});
flush();
//tick(500);
expect(item).toEqual('bar'); // Expected '' to equal 'bar'.
}));
We can just move the test case inside the promise and add a done
parameter to the it function, after the done is executed the test case ends and the test will pass
describe('Testing tests', () => {
it(`nested promise testing`, (done) => {
let item = '';
const mockItem = {
promise: new Promise((resolveInner) => {
resolveInner(new Response(JSON.stringify({ foo: 'bar' })));
}),
};
Promise.resolve(mockItem.promise)
.then((response: any) => response.json())
.then((data) => {
console.log('data = ' + data.foo);
item = data.foo;
expect(item).toEqual('bar'); // Expected '' to equal 'bar'.
done();
});
});
});