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 Dec 29, 2021
1 parent 0ac21ac commit 2712eab
Show file tree
Hide file tree
Showing 22 changed files with 2,718 additions and 2,231 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.

8 changes: 8 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ NODE_MODULES ?= "./node_modules"
NODE_MODULES_BIN ?= "${NODE_MODULES}/.bin"

FROM_VERSION ?= $(shell yarn run -s version)
EXAMPLE_FILES := $(shell find "examples" -name "*.js")

############## HELP ##############

Expand Down Expand Up @@ -55,3 +56,10 @@ release: ##@release generates a new release
@git commit -m "chore(v${RELEASE_VERSION}): bump version to ${RELEASE_VERSION}"
@git tag -a "v${RELEASE_VERSION}" -m "version ${RELEASE_VERSION}"
@git push origin v${RELEASE_VERSION}

examples: ##@examples run examples files
@echo "${YELLOW}start to run all examples files"
@if [ ! -d "build" ]; then yarn tsc; fi;\
for file in $(EXAMPLE_FILES); do echo "\n\nRun $${file}"; node $${file}; done;\

.PHONY: examples
4 changes: 3 additions & 1 deletion definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export interface Internal {
levels?: LogLevel[]
level?: number
outputs?: OutputAdapter[]
globalContext?: unknown
globalContext?: Record<string, unknown>
isEnabled?(namespace: string, index: number): boolean
}

export type LogColor = 'red' | 'yellow' | 'blue' | 'white' | 'grey'
4 changes: 2 additions & 2 deletions examples/example1.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const logger = require('../index')
const logger = require('../build/index')

logger.setNamespaces('root:*')
logger.setLevel('debug')

const log = logger('root:testing')
const log = logger.createLogger('root:testing')
log.debug('sample message', {
foo: 'bar',
})
4 changes: 2 additions & 2 deletions examples/example2.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const logger = require('../index')
const logger = require('../build/index')

logger.setNamespaces('root:*')
logger.setLevel('debug')

const log = logger('root:testing')
const log = logger.createLogger('root:testing')
log.debug('ctxId', 'log with predefined context ID', {
foo: 'bar',
})
4 changes: 2 additions & 2 deletions examples/example3.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const logger = require('../index')
const logger = require('../build/index')

logger.setNamespaces('namespace:*')
logger.setLevel('debug')
//logger.setOutput(logger.outputs.json)

const log = logger('namespace:subNamespace')
const log = logger.createLogger('namespace:subNamespace')
log.debug('ctxId', 'Will be logged', { someData: 'someValue', someData2: 'someValue' })
4 changes: 2 additions & 2 deletions examples/example_context.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const logger = require('../index')
const logger = require('../build/index')

logger.setOutput(logger.outputs.pretty)
logger.setNamespaces('*')
logger.setLevel('info')
logger.setGlobalContext({ version: '2.0.0', env: 'dev' })

const log = logger('namespace')
const log = logger.createLogger('namespace')

log.warn('message', { someData: 'someValue' })
4 changes: 2 additions & 2 deletions examples/example_data.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const logger = require('../index')
const logger = require('../build/index')

logger.setOutput(logger.outputs.pretty)
logger.setNamespaces('namespace:*')
logger.setLevel('info')

const log = logger('namespace:subNamespace')
const log = logger.createLogger('namespace:subNamespace')

log.warn('message', { someData: 'someValue' })
4 changes: 2 additions & 2 deletions examples/example_pretty.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const logger = require('../index')
const logger = require('../build/index')

logger.setNamespaces('namespace:*')
logger.setLevel('debug')
logger.setOutput(logger.outputs.pretty)

const log = logger('namespace:subNamespace')
const log = logger.createLogger('namespace:subNamespace')
log.debug('ctxId', 'Will be logged', { someData: 'someValue', someData2: 'someValue' })
113 changes: 53 additions & 60 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,11 +100,8 @@ 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)
internals.level = internals.levels?.indexOf(level)

syncLoggers()
}
Expand All @@ -131,7 +128,7 @@ export const setOutput = (outputs?: OutputAdapter[] | OutputAdapter): void => {
* even those from third party libraries if they use this module.
* @param {Object} context - The object holding default context data
*/
export const setGlobalContext = (context: unknown): void => {
export const setGlobalContext = (context: Record<string, unknown>): void => {
internals.globalContext = context
}

Expand All @@ -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 @@ -215,7 +187,7 @@ export const log = (namespace: string, level: LogLevel, contextId?: string | nul
contextId = contextId || id()
const time = new Date()
const logInstance: LogInstance = { level, time, namespace, contextId }
logInstance.meta = Object.assign({}, internals.globalContext)
if (internals.globalContext) logInstance.meta = Object.assign({}, internals.globalContext)
if (message) logInstance.message = message
if (data) logInstance.data = data

Expand All @@ -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',
}
Loading

0 comments on commit 2712eab

Please sign in to comment.