November 24, 2022
TestsSource
- what happens with a value that has been consumed?
- whats a diff between yield and return?
- is getting the next item async or the item itself?
Source Code
The source code we wrote during the event.
asyncgenerators.spec.js
import {strict as assert} from 'assert';
describe('what happens with a value that has been consumed?', () => {
it('a yielded value is the same as the consumed value', async () => {
// Arrange
const yieldedValue = {answer: 42};
async function* generatorFunction() {
yield yieldedValue;
}
const generator = generatorFunction();
// Act
const {value: consumedValue} = await generator.next();
// Assert
assert.equal(yieldedValue, consumedValue);
});
});
describe('whats a diff between yield and return?', () => {
it('a return always ends the generator', async () => {
async function* generatorFunction() {
return;
}
const generator = generatorFunction();
const {done} = await generator.next();
assert.equal(done, true);
});
it('yielding one value doesnt end the generator', async () => {
async function* generatorFunction() {
yield 42;
}
const generator = generatorFunction();
const {done} = await generator.next();
assert.equal(done, false);
});
it('the generator ends when the function returns', async () => {
async function* generatorFunction() {
yield 42;
}
const generator = generatorFunction();
await generator.next();
const {done} = await generator.next();
assert.equal(done, true);
});
});
describe('is getting the next item async or the item itself?', () => {
it('an async generator next method returns a promise', () => {
async function* generatorFunction() {
}
const generator = generatorFunction();
const result = generator.next();
assert.equal(result instanceof Promise, true);
});
});