简体   繁体   English

在使用 Postgres、chai 和 mocha 时为节点 Rest api 编写单元测试的最佳方法?

[英]Best way to write unit test for Node Rest api while working with Postgres, chai and mocha?

I am working on node js rest api in which database is Postgres and we are not using any ORM.我正在研究节点 js rest api,其中数据库是 Postgres,我们没有使用任何 ORM。 How I am writing is as below which is hitting database for create and update我的写作方式如下,它正在点击数据库进行创建和更新

it('it should create customer', (done) => {
  const payload = {
    customerId: "test",
    customerName: "test",
    customerAddress: "Some place, NWZ"
  }
  chai
    .request(server)
    .post('/customer')
    .send(payload)
    .end((err, res) => {
      res.should.have.status(200);
      res.body.success.should.equal(true);
      done();
    });
});

Now I want to know that what is best way to write unit test cases?现在我想知道编写单元测试用例的最佳方法是什么 Like喜欢

  1. Should I write unit test cases by mocking api response excluding database query?我是否应该通过 mocking api 响应编写单元测试用例,不包括数据库查询?
  2. Or should I write unit test case which will hit database?或者我应该编写将命中数据库的单元测试用例?

Or in any way we can mock database?或者以任何方式我们可以模拟数据库? What is best way to do it?最好的方法是什么?

There is some debate regarding whether unit tests should hit database.关于单元测试是否应该命中数据库存在一些争论。 But in general, I would say hitting a real database in testing should be categories as integration test, not unit test.但总的来说,我会说在测试中打一个真正的数据库应该是集成测试的类别,而不是单元测试。

So for your question 2: I would say: no, you should not write unit test case that hit database.所以对于你的问题 2:我会说:不,你不应该编写命中数据库的单元测试用例。

Then for your question 1: yes, you should mocking api response, the library you could choose, eg sinon.然后对于您的问题 1:是的,您应该 mocking api 响应,您可以选择的库,例如 sinon。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM