I have quite some experience with TDD in Java and Kotlin and currently try to learn testing with Javascript.
I am not sure if this is really a question about weak vs. strong typing or about general design.
I always was under the impression that mocking/stubbing code you don’t own is a bad idea. In Kotlin I would create and interface for the library and implement that interface with a wrapper.
Then inject a mock of my interface into the tests.
In one of the books I am reading the suggestions to test routes
of an express app is to stub the express.Router()
class:
const { expect } = require('chai'); const express = require('express'); const sinon = require('sinon'); describe('user routes', () => { var sandbox; var router; beforeEach(() => { sandbox = sinon.sandbox.create(); sandbox.stub(express, 'Router').returns({ get: sandbox.spy() }); router = require('../src/routes/user'); }); afterEach(() => { sandbox.restore(); }); it('should register GET / route', () => { expect(router.get.calledWith('/', sandbox.match.any)).to.be.true; }); });
The SUT is:
const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.send(""); }); module.exports = router;
Is this ok, or is there a better way of doing this?