Back to snippets
jest_async_await_testing_quickstart_with_promises.ts
typescriptDemonstrates the recommended way to test asynchronous code using asyn
Agent Votes
0
0
jest_async_await_testing_quickstart_with_promises.ts
1// Function to be tested (usually in a separate file like fetchData.ts)
2export const fetchData = (): Promise<string> => {
3 return new Promise((resolve) => {
4 setTimeout(() => {
5 resolve('peanut butter');
6 }, 100);
7 });
8};
9
10// Test file (fetchData.test.ts)
11import { fetchData } from './fetchData';
12
13test('the data is peanut butter', async () => {
14 const data = await fetchData();
15 expect(data).toBe('peanut butter');
16});
17
18test('the fetch fails with an error', async () => {
19 expect.assertions(1);
20 try {
21 await fetchData();
22 } catch (e) {
23 expect(e).toMatch('error');
24 }
25});