Первый подход к async/await
- это стандартный JavaScript, где вы хотите запускать функцию асинхронно и можете ждать обещаний перед переносом на следующую строку.
it('it block in an async await way', async(done) => {
await waitForThisFunctionThatReturnsAPromiseBeforeCarringForward();
// do something, make assertions
const x = await getXFromAPromise(); // wait for getXFromAPromise() function to return the promise
// and assign the results to x
// do something, make assertions
done(); // call done to ensure you have run through the whole it block and tell Jasmine you're done
});
The fixture.whenStable
в основном ожидает, пока все обещания в стеке будут разрешены, прежде чем продолжить с утверждениями.
it('demonstration of fixture.whenStable', async(done) => {
// do some actions that will fire off promises
await fixture.whenStable(); // wait until all promises in the call stack have been resolved
// do some more assertions
done(); // call done to tell Jasmine you're done with this test.
});
Обратный вызов done не является обязательным, но я использую его для обеспечения лучшего проектирования (убедитесь, что он прошел через весь блок it ).
Edit ====================
Для обработки наблюдаемых я использую два метода.
async/await
с операторами take
и toPromise
, где вы берете первое излучение и конвертируете его в обещание. Не стесняйтесь добавлять другие операторы, такие как filter
, чтобы игнорировать некоторые выбросы перед take(1)
.
import { take } from 'rxjs/operators';
......
it('should do xyz', async done => {
const x = await component.observable$.pipe(take(1)).toPromise();
expect(x).toBe(....);
done();
});
Другой способ - subscribe
с done
обратным вызовом
it('should do xyz', done => {
component.observable$.subscribe(result => {
expect(result).toBe(...);
// call done here to ensure the test made it within the subscribe
// and did the assertions and to let Jasmine know you're done with the tests
done();
});
});