Skip to content

Instantly share code, notes, and snippets.

@edharmowongso
Last active August 23, 2020 10:39
Show Gist options
  • Save edharmowongso/056904edd84ac4e56839feaff486ef4b to your computer and use it in GitHub Desktop.
Save edharmowongso/056904edd84ac4e56839feaff486ef4b to your computer and use it in GitHub Desktop.
Prepare all test setup requirement, then define the main test scenario and it's children with using describe and it.
// Located inside __tests__ folder
require('dotenv').config()
// Call the mocked modules
const {
loggerModule: logger
} = require('./mocks/logger.mockedModules')
// Act as the assertion library
const chai = require('chai')
// For test setup (spies, mock, stub)
const sinon = require('sinon')
// Sinon lib assertion in Chai
const sinonChai = require('sinon-chai')
// To match array / object
const deepEqualInAnyOrder = require('deep-equal-in-any-order')
// Define method expect from Chai library
const { expect } = chai
// Optional - Define multiple test cases using each
const forEach = require('mocha-each')
// For controller scope
// Define method `mockReq` (mocking the request) & `mockRes` (mocking the response)
const { mockReq, mockRes } = require('sinon-express-mock')
// Implementing sinonChai & deepEqualInAnyOrder into Chai library
chai.use(sinonChai)
chai.use(deepEqualInAnyOrder)
// Describe the name of the file
// Expected format -> `{file name [Controller/Model/Helper]} [Controller/Model/Helper] test`
describe('Logger Controller test', function() {
// Describe the method you want to test
// Expected format -> `{method name} test`
describe('Create test', function() {
// Inside this tested method, define the general cases with describe
// In this case, there are two main cases (validation failed & passed)
describe('Joi validation failed', function() {
// Define several test cases using it
// For better writing in specs, we can use forEach
forEach([
[
'not sending logType attr in request params',
{ body: {} },
`"logType" is required`
],
[
'not sending message attr in request params',
{ body: { logType: 'info' } },
`"message" is required`
],
[
'sending invalid logType attr in request params',
{ body: { logType: 'aaaa' } },
`"logType" must be one of [info, error, warning]`
]
]).it('throws error if `%s`', async (_, params, msg) => {
// Remember the concept of AAA
// Arrange
let req = mockReq(params)
let res = mockRes()
let next = sinon.stub()
// Act
await logger.Create(req, res, next)
// Assert
expect(next.lastCall.args[0].details[0].message).eql(msg)
})
})
describe('Joi validation passed', function() {
// CODE
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment