typescript 如何测试express.js错误处理程序?

tjjdgumg  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(113)

我试图用TypeScript和Sinon测试这个函数的失败情况,但是我不知道怎么做。有帮助吗?

public async findById(id: number): Promise<UserModel> {
    const user = await this._userModel.findByPk(id);
    if (!user) throw new NotFound('User not found');
    return user;
  }
5kgi1eie

5kgi1eie1#

弄清楚并最终创建单元和集成测试:
整合:

it('should fail to find user by id', async function () {
   Sinon.stub(Model, 'findByPk').resolves(null);
   const response = await chai.request(app).get('/users/999').send({
     params: 999,
   });

   expect(response.status).to.equal(404);
});

单位:

it('should fail to find user by id', async function () {
  sinon.stub(Model, 'findByPk').resolves(null);

  try {
    await userService.findById(999);
  } catch (e) {
    const error = e as Error;
    expect(error).to.be.instanceOf(NotFound);
    expect(error.message).to.equal('User not found');
  }
});

相关问题