Async Testing in JavaScript: Done, Promises, and Async/Await

⏱️ 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗖𝗼𝗱𝗲 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Async testing in JavaScript is one of those areas where things look correct — but fail silently if done wrong. 📞 🔙 𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸-𝗕𝗮𝘀𝗲𝗱 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 When your function depends on callbacks, your test must explicitly tell the test runner when it's done. it("should fetch data (callback)", (done) => {  fetchData((err, data) => {  if (err) return done(err);  expect(data).toBe("hello");  done(); // critical!  }); }); ❯❯❯❯ If you see callbacks → use done carefully. ⏳ 𝗣𝗿𝗼𝗺𝗶𝘀𝗲-𝗕𝗮𝘀𝗲𝗱 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 Cleaner than callbacks, but still easy to mess up. You must return the promise from your test. it("should fetch data (promise)", () => {  return expect(fetchData()).resolves.toBe("hello"); }); ❯❯❯❯ Always return the promise OR use .resolves/.rejects. 🔄 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 (𝗠𝗼𝗱𝗲𝗿𝗻 𝗦𝘁𝗮𝗻𝗱𝗮𝗿𝗱) The cleanest and most readable approach. it("should fetch data (async/await)", async () => {  const data = await fetchData();  expect(data).toBe("hello"); }); Handling errors - it("should throw error", async () => {  await expect(fetchData()).rejects.toThrow("error"); }); ❯❯❯❯ If you use async, always use await where needed. ✍ 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 ♦️ Callbacks → use done() ♦️ Promises → return the promise ♦️ Async/Await → use await properly ♦️ Always test both success AND failure paths. 👉 We’ll dive deeper into 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝘀𝗲𝘀 𝗼𝗳 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 in the upcoming posts. Stay tuned!! 🔔 Follow Nitin Kumar for daily valuable insights on LLD, HLD, Distributed Systems and AI. ♻️ Repost to help others in your network. #javascript #nodejs #testing #tdd #mocha #sinon #async

  • text

To view or add a comment, sign in

Explore content categories