简介
jasmine-promise-matchers
是一个 npm
包,可以在 Jasmine 测试框架中使用,方便地测试异步代码,尤其是异步代码返回的 Promise
实例。它提供了一些自定义的匹配器,方便我们在测试异步代码时更加简便,可读性更强。
在实际项目中,我们经常需要写测试来验证我们的代码是否能够正常运行。但对于异步代码的测试,我们有时很难写出来,此时 jasmine-promise-matchers
就成为了我们的一个好帮手。
安装
要使用 jasmine-promise-matchers
,首先需要安装它。
npm install --save-dev jasmine-promise-matchers
使用
使用 jasmine-promise-matchers
需要添加一个脚本文件。在 jasmine
的配置文件中,添加:
-- -------------------- ---- ------- -- ------------- -------------- - -------- -------- - ------------ -- ------- ------ - ------------------------------------------------------------------------- -- ----- -- ---- -- -- ------- -- -展开代码
然后在测试用例中使用 require('jasmine-promise-matchers')
即可:
-- -------------------- ---- ------- ----- ---------------------- - ----------------------------------- ------------ ---------------- -- -- - ------------- -- - ------------------------------------------- -- ----- -- ---------- ------ ----- ----- -- -- - ----- --- - ----- ----------------------- ----------------------- -- ---------- ----- ----- ---- ------- ---- --- ---------- ----- -- -- - ----- ----------------------------------------------------------- --- --------- -- ---------- --- ----- ------- ----- -- -- - ----- ------------------------------------------- -- --展开代码
匹配器
jasmine-promise-matchers
包括以下几个匹配器:
toBeResolved()
验证 Promise
是否已解决(即 resolve()
调用)
it('should not throw error', async () => { await expect(exampleService.baz()).toBeResolved() })
toBeResolvedWith(expected)
验证 Promise
的实际值 resolve()
是否等于期望值 expected
it('should return foo', async () => { const val = await exampleService.getFoo() expect(val).toBe('foo') })
toBeRejected()
验证 Promise
是否已挂起(即 reject()
调用)
it('should throw error with message `400 Bad Request`', async () => { await expect(exampleService.postBar()).toBeRejected() })
toBeRejectedWithError(expected)
验证 Promise
抛出错误的消息是否等于期望值 expected
it('should throw error with message `400 Bad Request`', async () => { await expect(exampleService.postBar()).toBeRejectedWithError('400 Bad Request') })
toBeRejectedWithErrorMatching(expected)
验证 Promise
抛出错误的消息是否与期望值相匹配
it('should throw error with message `Invalid username`', async () => { await expect(exampleService.postFooBar()).toBeRejectedWithErrorMatching(/Invalid username/) })
结束语
jasmine-promise-matchers
可以方便我们更加简便地测试异步代码。它提供了一些很有用的自定义匹配器来方便我们编写测试用例,提升了代码可读性。
同时,我们也应该注意,对于 Promise
的使用,我们应该遵循一定的规范,写出具有健壮性的异步代码。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/5eedcbe4b5cbfe1ea06126ac