sinonjs / sinon

Test spies, stubs and mocks for JavaScript.
https://sinonjs.org/
Other
9.61k stars 769 forks source link

Use sinon to mock node-mssql #2541

Closed cklat closed 11 months ago

cklat commented 11 months ago

Describe the bug

I'm trying to mock a database connection for which I'm using the tedious node-mssql library (https://github.com/tediousjs/node-mssql)

More concretely, I'm trying to stub the ConnectionPool method of the library as follows (with mocha and chai):

mockDB.test.ts

import * as sinon from 'sinon';
import * as mssql from 'mssql';

describe('EmployeeDiscountController', function () {
   beforeEach(async function() {
    sinon.stub(mssql, 'ConnectionPool').returns({
      ConnectionPool: sinon.stub().returns({
        request: () => {},
        connect: () => {}
      })
    });
  });
});

(I skipped all the unnecessary parts in the code.)

Unfortunately, I get the following error:

TypeError: Descriptor for property ConnectionPool is non-configurable and non-writable
    at assertValidPropertyDescriptor (node_modules\sinon\lib\sinon\stub.js:138:15)
    at Function.stub (node_modules\sinon\lib\sinon\stub.js:89:5)
    at Object.stub (node_modules\sinon\lib\sinon\sandbox.js:389:39)

Do you know why this is?

I saw a PR that would resolve this issue but as I am using the latest sinon version (15.2.0) this problem seems to persist for me.

Is it advisable to even use sinon to mock such packages? I don't very little experience in writing tests and am actually using sinon the first time.

Thank you very much for your help!

fatso83 commented 11 months ago

Hi, this is is more less exactly what I covered in this new article I just wrote on different approaches to testing. You can see if you find your answer there: https://github.com/sinonjs/sinon/pull/2540

Basically, the value you are trying to stub is not a value, but a kind of getter. You can read about these here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

My article covers different approaches on how you can attach this (I cover 3 very different approaches, from tool configuration, external loaders and through exposing your code).