Skip to content

Commit

Permalink
feat(jest): convert test files to ts
Browse files Browse the repository at this point in the history
  • Loading branch information
tduyng committed Nov 29, 2021
1 parent 0ac21ac commit 5696add
Show file tree
Hide file tree
Showing 14 changed files with 2,691 additions and 2,213 deletions.
51 changes: 51 additions & 0 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: Node.js CI

on: [push, pull_request]

jobs:
build:
runs-on: ubuntu-latest

strategy:
matrix:
node-version: [12.x, 14.x, 16.x]

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn config get cacheFolder)"

- uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ matrix.node-version }}-${{ hashFiles('**/yarn.lock') }}
restore-keys: ${{ runner.os }}-yarn-
- name: Install dependencies
if: steps.yarn-cache-dir-path.outputs.cache-hit != 'true'
run: yarn install
- run: yarn lint
- run: yarn check-fmt
- run: yarn tsc
- run: yarn test-cover
env:
CI: true
- name: Coveralls Parallel
uses: coverallsapp/[email protected]
with:
github-token: ${{ secrets.github_token }}
parallel: true
coverall:
needs: build
runs-on: ubuntu-latest
steps:
- name: Coveralls Finished
uses: coverallsapp/[email protected]
with:
github-token: ${{ secrets.github_token }}
parallel-finished: true
15 changes: 0 additions & 15 deletions .travis.yml

This file was deleted.

2 changes: 2 additions & 0 deletions definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ export interface Internal {
globalContext?: unknown
isEnabled?(namespace: string, index: number): boolean
}

export type LogColor = 'red' | 'yellow' | 'blue' | 'white' | 'grey'
107 changes: 50 additions & 57 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Internal, Logger, LogLevel, LogInstance, NameSpaceConfig, OutputAdapter
import * as outputAdapters from './output_adapters'
import * as outputUtils from './output_utils'

const internals: Internal = {}
export const internals: Internal = {}

/**
* @typedef {Function} LoggerLogFunction
Expand Down Expand Up @@ -85,7 +85,7 @@ export const setNamespaces = (namespace: string): void => {
const parsedNamespace = parseNamespace(name)
if (!parsedNamespace) return

internals.namespaces?.push(parsedNamespace)
internals.namespaces!.push(parsedNamespace)
})

syncLoggers()
Expand All @@ -100,9 +100,6 @@ export const setLevel = (level: LogLevel): void => {
throw new Error(`Invalid level: '${level}'`)
}

// expose level name
exports.level = level

// internally store corresponding level index
internals.level = internals.levels.indexOf(level)

Expand Down Expand Up @@ -144,31 +141,6 @@ export const id = (): string => {
return uuidv4()
}

/************* INTERNALS *************/
internals.loggers = {}
internals.levels = ['trace', 'debug', 'info', 'warn', 'error', 'none']

/**
* List of output functions
* @type {Array<OutputAdapter>}
*/
internals.outputs = [outputAdapters.json]

/**
* Internally we store level index as it's quicker to compare numbers
*/
internals.level = undefined

/**
* Internally store parsed namespaces,
* `exports.namespaces` contains raw config.
*
* @type {Array<NamespaceConfig>}
*/
internals.namespaces = []

internals.globalContext = {}

/**
* Parse a namespace to extract level, namespace (eg: ns1:subns1=info)
* @param {string} namespace
Expand Down Expand Up @@ -232,29 +204,6 @@ export const write = (logInstance: LogInstance): void => {
})
}

/**
* True if both namespace and level are enabled.
* @param {String} namespace
* @param {String} level
* @return {Boolean} true if enabled
*/
internals.isEnabled = (namespace, level): boolean => {
let nsLevel = internals.level || 0
let nsMatch = false

_.forEachRight(internals.namespaces, (ns) => {
if (ns.regex?.test(namespace)) {
nsMatch = true
if (ns.level) {
nsLevel = ns.level
return false
}
}
})

return nsMatch && level >= nsLevel
}

/**
* Remove all properties but levels.
* Levels contains a function that does nothing if namespace or level is disable.
Expand All @@ -277,9 +226,6 @@ export const syncLogger = (logger: Logger, namespace: string): Logger => {
logger[level] = () => {}
} else {
enabledLevels[level] = true

// @TODO: to fix this, try to make optional method in LogMethod interface
// @ts-ignore
logger[level] = (contextId: string, message: string, data?: unknown) => {
log(namespace, level, contextId, message, data)
}
Expand All @@ -302,12 +248,59 @@ export const syncLoggers = () => {
})
}

/************* INTERNALS *************/
internals.loggers = {}
internals.levels = ['trace', 'debug', 'info', 'warn', 'error', 'none']
/**
* List of output functions
* @type {Array<OutputAdapter>}
*/
internals.outputs = [outputAdapters.json]

/**
* Internally we store level index as it's quicker to compare numbers
*/
internals.level = undefined

/**
* Internally store parsed namespaces,
* `exports.namespaces` contains raw config.
*
* @type {Array<NamespaceConfig>}
*/
internals.namespaces = []

internals.globalContext = {}

/**
* True if both namespace and level are enabled.
* @param {String} namespace
* @param {String} level
* @return {Boolean} true if enabled
*/
internals.isEnabled = (namespace, level): boolean => {
let nsLevel = internals.level || 0
let nsMatch = false

_.forEachRight(internals.namespaces, (ns) => {
if (ns.regex?.test(namespace)) {
nsMatch = true
if (ns.level) {
nsLevel = ns.level
return false
}
}
})

return nsMatch && level >= nsLevel
}

/************* INIT *************/
const namespaces = process.env.LOGS || '*'
const logLevel: LogLevel = (process.env.LOG_LEVEL as LogLevel) || 'warn'

setNamespaces(namespaces)
setLevel(logLevel)

export { internals, outputAdapters as outputs, setOutput as setOutputs }
export { outputAdapters as outputs }
export { outputAdapters, outputUtils }
12 changes: 12 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
testRegex: '.*\\.test\\.ts$',
transform: {
'^.+\\.(t|j)s$': 'ts-jest',
},
collectCoverageFrom: ['index.ts', 'output_*.ts'],
coverageDirectory: './coverage',
}
40 changes: 21 additions & 19 deletions output_adapters.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
import _ from 'lodash'
import colors from 'colors/safe'
const prettyOutput = require('prettyoutput')
import prettyOutput from 'prettyoutput'

import * as outputUtils from './output_utils'
import { LogInstance, Output } from './definitions'
import { LogColor, LogInstance, LogLevel, Output } from './definitions'

/**
* Object mapping log color and log level
* @param {Record<LogLevel, LogColor>} levelColorMap
*/
export const levelColorMap: Record<LogLevel, LogColor> = {
none: 'red',
error: 'red',
warn: 'yellow',
info: 'blue',
debug: 'white',
trace: 'grey',
}

/**
* Make sure that we get a 2 digit number by beginning with a 0 if length < 2
* @param {number|string} num
* @returns {string}
*/
export const twoDigitNumber = (num?: number | string): string => {
return `${num}`.length < 2 ? `0${num}` : `${num}`
return num != null ? (`${num}`.length < 2 ? `0${num}` : `${num}`) : ''
}

/**
Expand All @@ -25,7 +38,7 @@ export const prettyTime = (time?: Date): string | undefined => {
const year = twoDigitNumber(time.getFullYear())
const month = twoDigitNumber(time.getMonth() + 1)
const day = twoDigitNumber(time.getDate())
const hours = twoDigitNumber(time.getHours())
const hours = twoDigitNumber(time.getUTCHours())
const minutes = twoDigitNumber(time.getMinutes())
const seconds = twoDigitNumber(time.getSeconds())

Expand All @@ -38,29 +51,18 @@ export const prettyTime = (time?: Date): string | undefined => {
*/
export const pretty = (logInstance: LogInstance): void => {
const time = prettyTime(logInstance.time)
const defaultLevel = logInstance.level || 'error'

const levelColorMap = {
error: 'red',
warn: 'yellow',
info: 'blue',
debug: 'white',
trace: 'grey',
}

// @TODO: to fix the type of colors
// @ts-ignore
const levelColor = levelColorMap[logInstance.level] || 'red'
const levelColor = levelColorMap[defaultLevel]

const infos = `${time} (${logInstance.namespace}) [${logInstance.level}] : `
const infos = `${time} (${logInstance.namespace}) [${defaultLevel}] : `

const output: Output = {}
if (!_.isEmpty(logInstance.contextId)) output.contextId = logInstance.contextId
if (!_.isEmpty(logInstance.meta)) output.meta = logInstance.meta
if (!_.isEmpty(logInstance.data)) output.data = logInstance.data

// @TODO: to fix the type of colors
// @ts-ignore
const result = `${infos}${colors[levelColor](logInstance.message)}\n${prettyOutput(output, { maxDepth: 6 }, 2)}`
const result = `${infos}${colors[levelColor](logInstance.message || '')}\n${prettyOutput(output, { maxDepth: 6 }, 2)}`

process.stdout.write(result)
process.stdout.write('\n')
Expand Down
24 changes: 6 additions & 18 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,42 +34,30 @@
},
"devDependencies": {
"@commitlint/config-conventional": "8.x",
"@types/jest": "27.x",
"@types/lodash": "4.x",
"@types/node": "16.x",
"@types/sinon": "10.x",
"@types/uuid": "8.x",
"ava": "3.x",
"commitlint": "8.x",
"conventional-changelog-cli": "2.x",
"coveralls": "3.x",
"eslint": "6.x",
"husky": "4.x",
"nyc": "15.x",
"jest": "27.x",
"prettier": "2.x",
"sinon": "9.x",
"ts-jest": "27.x",
"ts-node": "10.x",
"typescript": "4.x"
},
"scripts": {
"fmt": "prettier --color --write \"{*,test/**/*}.{js,ts}\"",
"check-fmt": "prettier --list-different \"{*,test/**/*}.{js,ts}\"",
"tsc": "tsc -d",
"test": "ava",
"test-cover": "nyc ava",
"coverage": "nyc report --reporter=text-lcov | coveralls",
"test": "jest",
"test-cover": "jest --coverage",
"coverage": "jest --coverage --coverageReporters=text-lcov | coveralls",
"changelog": "conventional-changelog -p conventionalcommits -i CHANGELOG.md -s -r 0",
"version": "echo ${npm_package_version}",
"lint": "eslint ."
},
"ava": {
"files": [
"test/**/*.js"
],
"extensions": [
"js"
],
"require": [
"ts-node/register"
]
}
}
Loading

0 comments on commit 5696add

Please sign in to comment.