Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use sinon to mock node-mssql #2541

Closed
cklat opened this issue Aug 24, 2023 · 1 comment
Closed

Use sinon to mock node-mssql #2541

cklat opened this issue Aug 24, 2023 · 1 comment

Comments

@cklat
Copy link

cklat commented Aug 24, 2023

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
Copy link
Contributor

fatso83 commented Aug 24, 2023

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: #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).

@fatso83 fatso83 closed this as completed Aug 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants