博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Support Async Tests with JavaScripts Promises through async await Our testing
阅读量:7041 次
发布时间:2019-06-28

本文共 2084 字,大约阅读时间需要 6 分钟。

Support Async Tests with JavaScripts Promises through async await

Our testing framework works great for our synchronous test. What if we had some asynchronous functions that we wanted to test? We could make our callback functions async, and then use the await keyword to wait for that to resolve, then we can make our assertion on the result and the expected.

Let’s make our testing framework support promises so users can use async/await.

提取码:36e3复制代码

Transcript

Our testing framework works great for our synchronous test. What if we had some asynchronous functions that we wanted to test? We could make our callback functions async, and then use the await keyword to wait for that to resolve, then we can make our assertion on the result and the expected.

async-await.js

test('sumAsync adds numbers asynchronously', async () => {  const result = await sumAsync(3, 7)  const expected = 10  expect(result).toBe(expected)})test('subtractAsync subtracts numbers asynchronously', async () => {  const result = await subtractAsync(7, 3)  const expected = 4  expect(result).toBe(expected)})复制代码

This approach has a little bit of a problem though. If we run our test, we are going to see that they both pass, and then after that, we have an UnhandledPromiseRejectionWarning. That is the actual error coming from our sumAsync function being broken.

Because this is an async function, this function will return a promise. When this error is thrown, it's going to reject that promise. Here inside of our test function, this callback is going to return a promise. If we turn this test into an async function, and then await that callback, if that promise is rejected, then we'll land in our catch block.

If no error is thrown, then we'll continue on inside the try block. This will work for both our synchronous and our asynchronous tests.

async function test(title, callback) {  try {    await callback()    console.log(`✓ ${title}`)  } catch (error) {    console.error(`✕ ${title}`)    console.error(error)  }}复制代码

With that, we can run our test again, and things happen exactly as we expect.

转载地址:http://voaal.baihongyu.com/

你可能感兴趣的文章
nginx 访问日志分析
查看>>
RabbitMQ之消息确认机制(事务+Confirm)
查看>>
给出一个数组,计算数组中少了哪个数据的实现
查看>>
USB-232卡 配置
查看>>
C#窗体程序皮肤设置
查看>>
T-SQL.字符串函数
查看>>
mysql慢查询
查看>>
offices文件打开乱码问题如何处理
查看>>
抓屏程序
查看>>
many-to-many出现的问题
查看>>
第5章 配置邮箱服务
查看>>
node.js的一个简单框架
查看>>
PPT如何保存还原已剪裁图片的原始版本
查看>>
lnmp一键安装之-php
查看>>
ajax 同步和异步的区别
查看>>
linux shell单引号、双引号及无引号区别(考试题答案系列)--看到这篇文章之后我豁然开朗...
查看>>
排错 zabbix-agent 主机重启无法被监控
查看>>
win10操作系统
查看>>
Mutual Funds引起的一桩桩血案
查看>>
zabbix如何监控nginx性能
查看>>