testjavascript / nodejs-integration-tests-best-practices

✅ Beyond the basics of Node.js testing. Including a super-comprehensive best practices list and an example app (March 2024)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Stub inside beforeAll

DanielGluskin opened this issue · comments

Here we use sinon.stub in beforeAll. This way we provide only one stub for the whole suite, which cannot be restored later.

Should we always stub inside beforeEach or the arrange phase but not in beforeAll?

Not sure I understand, can you please elaborate?

@DanielGluskin I think we do this now, right?

please refer here, what are your thoughts on the setup (beforeAll)? I think it is a bit problematic, as

  • we must initialize the stub before we initialize the app itself.
  • the stub is permanent, if we use sinon.restore() it won't be cleaned up (the same app instance will still be using it).
  • we might want to stub differently for each test.
  • we stub in beforeAll, not beforeEach.

I think a solution like this will be cleaner -

test('When user is not authenticated, Then ... ', () => {
   // arrange
   sinon.stub(authenticationMiddleware, 'authenticationMiddleware').callsFake((req, res, next) => res.status(401).end())

test('When user is authenticated, Then ... ', () => {
   // arrange
   sinon.stub(authenticationMiddleware, 'authenticationMiddleware').callsFake((req, res, next) => next())