describe('scope ',()=>{it('works with async',async ()=>{/* Some async code testing. */});});
请注意,内部的函数describe不是async,但外部的函数it是。
先放入一些数据进行测试
有时我们需要预先填充测试数据库,以便有一些数据可供使用。我将向您展示两种实现方法:
a. 在每个测试中添加所需数据
请检查以下代码:
it('should retrieve the correct product if id matches',async ()=>{// Seed.constcreatedIphone=awaitproductModel.create(productIphone);// testconstfoundProduct=awaitproductService.getById(createdIphone.id);expect(foundProduct.id).toBe(createdIphone.id);expect(foundProduct.name).toBe(productIphone.name);});
beforeEach(async ()=>awaitcreateProducts());afterEach(async ()=>awaitdbHandler.clearDatabase());describe('product ',()=>{it('test that needs data',async ()=>{});it('another test that needs data',async ()=>{});});
it('should retrieve the correct product if id matches',async ()=>{constfoundProduct=awaitproductService.getById(productIphoneId);expect(foundProduct.id).toBe(productIphoneId);expect(foundProduct.name).toBe(productIphone.name);});
使用resolve来等待结果
另一种测试异步函数结果的方法是使用 `--wait`,resolves这将导致 Jest 等待异步函数执行完毕。
在以下示例中,我们等待getById问题解决,然后检查结果是否为空:
it('should return null if nothing is found',async ()=>{// mongoose.Types.ObjectId() generates a new ID that won't exist in the current database.awaitexpect(productService.getById(mongoose.Types.ObjectId())).resolves.toBeNull();});
测试错误处理
测试函数是否抛出错误
我们可以期望异步函数不会抛出错误,如下所示:
it('can be created correctly',async ()=>{expect(async ()=>awaitproductService.create(productComplete)).not.toThrow();});
it('requires name and price',async ()=>{awaitexpect(productService.create(productMissingName)).rejects.toThrow(mongoose.Error.ValidationError);awaitexpect(productService.create(productMissingPrice)).rejects.toThrow(mongoose.Error.ValidationError);});