1

I am working on node js rest api in which database is Postgres and we are not using any 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 ?
  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 ?

1 Answer 1

1

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.

Then for your question 1: yes, you should mocking api response, the library you could choose, e.g. sinon.

---- Updated ----

There is an article regarding the topic, if you are interested, please refer to the following: Hitting Real Database? Unit Test and Integration Test for RESTful API in Nodejs Environment

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.