smartpromise/test/test.readme.node.ts

58 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2023-04-04 20:22:57 +02:00
import * as smartpromise from '../ts/index.js';
import { tap, expect } from '@push.rocks/tapbundle';
2021-05-31 13:02:22 +02:00
tap.test('simple deferred should resolve with correct value', async () => {
const done = smartpromise.defer<string>();
let result: string | undefined;
done.promise.then((stringArg) => {
result = stringArg;
});
done.resolve('hello');
2021-05-31 13:02:22 +02:00
await done.promise;
expect(result).toEqual('hello');
});
2021-05-31 13:02:22 +02:00
tap.test('deferred should work with async functions and track status/duration', async () => {
const myAsyncFunction = async (): Promise<string> => {
const done = smartpromise.defer<string>();
setTimeout(() => {
done.resolve('hi');
}, 100); // reduced timeout for testing
expect(done.status).toEqual('pending');
await done.promise;
expect(done.status).toEqual('fulfilled');
expect(done.duration).toBeGreaterThan(0);
return done.promise;
};
const result = await myAsyncFunction();
expect(result).toEqual('hi');
2021-05-31 13:02:22 +02:00
});
tap.test('resolvedPromise should resolve immediately with correct value', async () => {
const message = `I'll get logged to console soon`;
const result = await smartpromise.resolvedPromise(message);
expect(result).toEqual(message);
});
2021-05-31 13:02:22 +02:00
tap.test('rejectedPromise should reject with correct error message', async () => {
const errorMessage = 'what a lovely error message';
let caught = false;
try {
await smartpromise.rejectedPromise(errorMessage);
} catch (err) {
caught = true;
expect(err).toEqual(errorMessage);
}
expect(caught).toEqual(true);
});
2021-05-31 13:02:22 +02:00
export default tap.start();