'Mock variable loaded via require()

I have a variable as follows:

// MyModule.js
export const secret: process.env.SECRET

This secret is required in a module that I'm currently testing.

const verifyToken = (req, res, next) => {
    // does stuff 
}

While testing I want to replace the value of secret. I thought about using sinon, yet I seem unable to succeed with it.

Here's my approach:

describe("verifyToken", () => {
    it("should forward a request containing a valid token", async () => {
        let config = require("MyModule.js")
        let req = mockRequest("")
        let res = mockResponse()

        sinon.stub(config, "secret").returns("MyTestSecret")

        await authJwt.verifyToken(req, res, next)

        expect(res.status).to.have.not.been.called
        expect(next).to.be.called
    })
})

Can someone elabroate on what I'm doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source