Home > Blockchain >  How do I test a class's method that has arguments using sinon.js
How do I test a class's method that has arguments using sinon.js

Time:09-27

Hi I am using sequelize ORM with Postgres database for this node.js express.js app. As for testing I am using mocha, chai and sinon.

I am trying to complete a test for a class's method. The class instant i call it userService and the method is findOneUser .. This method has got an argument id .. So in this moment I want to test for a throw error the test works if I dont put an argument. That means this test is obviously not complete.

Here is the class method I want to test

userService.js

module.exports = class UserService {

  async findOneUser(id) {
    try {
      const user = await User.findOne({ where: { id: id } }); // if null is returned error is thrown

      if (!user) {
        throw createError(404, "User not found");
      }
      return user;
    } catch (err) {
      throw err
    }
  }
}

And here is my test code

userService.spec.js

describe.only("findOne() throws error", () => {
  let userResult;
  const error = customError(404, "User not found"); // customError is a function where I am throwing both status code and message
      before("before hook last it block issue withArgs" , async () => {

        // mockModels I have previously mocked all the models 
        mockModels.User.findOne.withArgs({ where: { id: fakeId } }).resolves(null); // basically have this called and invoked from calling the method that it is inside of based on the argument fakeId

        userResult = sinon.stub(userService, "findOneUser").throws(error); //            
  • Related