-
-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
19 changed files
with
6,074 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
module.exports = { | ||
parser: '@typescript-eslint/parser', | ||
extends: [ | ||
'eslint:recommended', | ||
'plugin:react/recommended', | ||
'plugin:@typescript-eslint/recommended', | ||
'prettier', | ||
'plugin:prettier/recommended', | ||
], | ||
env: { | ||
node: true, | ||
es6: true, | ||
}, | ||
plugins: ['@typescript-eslint', 'prettier'], | ||
parserOptions: { | ||
ecmaVersion: 2019, | ||
sourceType: 'module', | ||
}, | ||
rules: { | ||
'@typescript-eslint/explicit-module-boundary-types': 0, | ||
'@typescript-eslint/explicit-function-return-type': 0, | ||
'@typescript-eslint/interface-name-prefix': 0, | ||
'@typescript-eslint/no-explicit-any': 0, | ||
'@typescript-eslint/no-var-requires': 0, | ||
'@typescript-eslint/ban-ts-comment': 0, | ||
'@typescript-eslint/ban-ts-ignore': 0, | ||
'@typescript-eslint/camelcase': 0, | ||
'@typescript-eslint/no-unused-vars': [ | ||
'error', | ||
{ | ||
argsIgnorePattern: '^_', | ||
ignoreRestSiblings: true, | ||
}, | ||
], | ||
'no-prototype-builtins': 0, | ||
'prefer-spread': 0, | ||
'no-unused-vars': 0, | ||
'no-extra-boolean-cast': 0, | ||
'no-console': ['error', { allow: ['warn', 'error'] }], | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
### Node template | ||
# Logs | ||
logs | ||
*.log | ||
npm-debug.log* | ||
yarn-debug.log* | ||
yarn-error.log* | ||
lerna-debug.log* | ||
|
||
# Diagnostic reports (https://nodejs.org/api/report.html) | ||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json | ||
|
||
# Runtime data | ||
pids | ||
*.pid | ||
*.seed | ||
*.pid.lock | ||
|
||
# Coverage directory used by tools like istanbul | ||
coverage | ||
*.lcov | ||
|
||
# Dependency directories | ||
node_modules/ | ||
|
||
# TypeScript cache | ||
*.tsbuildinfo | ||
|
||
# Optional npm cache directory | ||
.npm | ||
|
||
# Optional eslint cache | ||
.eslintcache | ||
|
||
# Optional REPL history | ||
.node_repl_history | ||
|
||
# Output of 'npm pack' | ||
*.tgz | ||
|
||
# Yarn Integrity file | ||
.yarn-integrity | ||
|
||
# dotenv environment variables file | ||
.env | ||
.env.test | ||
|
||
# Stores VSCode versions used for testing VSCode extensions | ||
.vscode-test | ||
|
||
# yarn v2 | ||
.yarn/cache | ||
.yarn/unplugged | ||
.yarn/build-state.yml | ||
.yarn/install-state.gz | ||
.pnp.* | ||
|
||
.idea | ||
dist |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
_ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
#!/bin/sh | ||
. "$(dirname "$0")/_/husky.sh" | ||
|
||
yarn lint-staged |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"printWidth": 100, | ||
"semi": true, | ||
"singleQuote": true, | ||
"trailingComma": "es5", | ||
"arrowParens": "always" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
const packageJson = require('./package.json'); | ||
|
||
module.exports = { | ||
name: packageJson.name, | ||
displayName: packageJson.name, | ||
testEnvironment: 'node', | ||
preset: 'ts-jest', | ||
testMatch: ['<rootDir>/tests/**/?(*.)+(spec|test).[jt]s?(x)'] | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
{ | ||
"name": "knex-mock-client", | ||
"version": "1.0.0", | ||
"description": "A mock client for knex which allows you to write tests with DB interactions", | ||
"main": "dist/index.js", | ||
"author": "felixmosh", | ||
"license": "MIT", | ||
"engines": { | ||
"node": ">=12" | ||
}, | ||
"scripts": { | ||
"start": "ts-node-dev src/index.ts", | ||
"build": "rm -rf dist && tsc", | ||
"test": "jest test", | ||
"version": "auto-changelog -p && git add CHANGELOG.md", | ||
"release": "release-it", | ||
"prepare": "npm run build" | ||
}, | ||
"devDependencies": { | ||
"@types/faker": "^5.5.3", | ||
"@types/jest": "^26.0.23", | ||
"@types/lodash.clonedeep": "^4.5.6", | ||
"@types/node": "^15.0.2", | ||
"@typescript-eslint/parser": "^4.22.1", | ||
"auto-changelog": "^2.2.1", | ||
"eslint": "^7.25.0", | ||
"eslint-config-prettier": "^8.3.0", | ||
"eslint-plugin-prettier": "^3.4.0", | ||
"faker": "^5.5.3", | ||
"husky": "^6.0.0", | ||
"jest": "^26.6.3", | ||
"knex": "^0.95.4", | ||
"lint-staged": "^10.5.4", | ||
"prettier": "^2.2.1", | ||
"ts-jest": "^26.5.6", | ||
"ts-node-dev": "^1.1.6", | ||
"typescript": "^4.2.4" | ||
}, | ||
"lint-staged": { | ||
"*.ts": [ | ||
"prettier --write", | ||
"eslint --fix" | ||
] | ||
}, | ||
"release-it": { | ||
"git": { | ||
"changelog": "npx auto-changelog --stdout --commit-limit false -u --template https://raw.githubusercontent.com/release-it/release-it/master/templates/changelog-compact.hbs" | ||
}, | ||
"hooks": { | ||
"after:bump": "npx auto-changelog -p" | ||
}, | ||
"github": { | ||
"release": true | ||
} | ||
}, | ||
"dependencies": { | ||
"lodash.clonedeep": "^4.5.0" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import knex, { Knex } from 'knex'; | ||
import { RawQuery } from '../types/knex'; | ||
import { Tracker, TrackerConfig } from './Tracker'; | ||
|
||
export class MockClient extends (knex as any).Client { | ||
static tracker: Tracker; | ||
public readonly isMock = true; | ||
|
||
constructor(config: Knex.Config & { mockClient: TrackerConfig }) { | ||
super(config); | ||
|
||
MockClient.tracker = new Tracker(config.mockClient); | ||
} | ||
|
||
public acquireConnection() { | ||
return Promise.resolve({ __knexUid: 1, fakeConnection: true }); | ||
} | ||
|
||
public releaseConnection() { | ||
return Promise.resolve(); | ||
} | ||
|
||
public processResponse(response: any) { | ||
return response; | ||
} | ||
|
||
public _query(_connection: any, rawQuery: RawQuery) { | ||
// @ts-ignore | ||
rawQuery.method = rawQuery.method === 'del' ? 'delete' : rawQuery.method; | ||
return MockClient.tracker._handle(rawQuery); | ||
} | ||
} | ||
|
||
Object.assign(MockClient.prototype, { | ||
driverName: MockClient.name, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
import cloneDeep from 'lodash.clonedeep'; | ||
import { RawQuery } from '../types/knex'; | ||
import { queryMethods } from './constants'; | ||
|
||
export interface TrackerConfig {} | ||
|
||
interface Handler { | ||
data: any | ((rawQuery: RawQuery) => any); | ||
match: (rawQuery: RawQuery) => boolean; | ||
errorMessage?: string; | ||
once?: true; | ||
} | ||
|
||
type QueryMethodType = typeof queryMethods[number]; | ||
type History = Record<QueryMethodType, RawQuery[]>; | ||
|
||
export class Tracker { | ||
public readonly history: History = { | ||
select: [], | ||
insert: [], | ||
update: [], | ||
delete: [], | ||
}; | ||
private readonly config: TrackerConfig; | ||
private responses = new Map<RawQuery['method'], Handler[]>(); | ||
|
||
public on = { | ||
select: this.prepareStatement('select'), | ||
insert: this.prepareStatement('insert'), | ||
update: this.prepareStatement('update'), | ||
delete: this.prepareStatement('delete'), | ||
}; | ||
|
||
constructor(trackerConfig: TrackerConfig) { | ||
this.config = trackerConfig; | ||
this.reset(); | ||
} | ||
|
||
public _handle(rawQuery: RawQuery): Promise<any> { | ||
return new Promise((resolve, reject) => { | ||
setTimeout(() => { | ||
const handlers = this.responses.get(rawQuery.method) || []; | ||
for (let i = 0; i < handlers.length; i++) { | ||
const handler = handlers[i]; | ||
|
||
if (handler.match(rawQuery)) { | ||
this.history[rawQuery.method].push(rawQuery); | ||
|
||
if (handler.errorMessage) { | ||
reject(new Error(handler.errorMessage)); | ||
} else { | ||
resolve(cloneDeep(handler.data)); | ||
} | ||
|
||
if (handler.once) { | ||
handlers.splice(i, 1); | ||
} | ||
return; | ||
} | ||
} | ||
|
||
reject(new Error(`No mock handler found`)); | ||
}, 0); | ||
}); | ||
} | ||
|
||
public reset() { | ||
this.resetHandlers(); | ||
this.resetHistory(); | ||
} | ||
|
||
public resetHandlers() { | ||
queryMethods.forEach((method) => this.responses.set(method, [])); | ||
} | ||
|
||
public resetHistory() { | ||
queryMethods.forEach((method) => (this.history[method].length = 0)); | ||
} | ||
|
||
private prepareMatcher(rawQueryMatcher: string | RegExp | Handler['match']): Handler['match'] { | ||
if (typeof rawQueryMatcher === 'string' && rawQueryMatcher) { | ||
return (rawQuery: RawQuery) => rawQuery.sql.includes(rawQueryMatcher); | ||
} else if (rawQueryMatcher instanceof RegExp) { | ||
return (rawQuery: RawQuery) => rawQueryMatcher.test(rawQuery.sql); | ||
} else if (typeof rawQueryMatcher === 'function') { | ||
return rawQueryMatcher; | ||
} | ||
|
||
throw new Error('Given invalid query matcher'); | ||
} | ||
|
||
private prepareStatement(queryMethod: QueryMethodType) { | ||
return (rawQueryMatcher: string | RegExp | Handler['match']) => { | ||
const matcher = this.prepareMatcher(rawQueryMatcher); | ||
return { | ||
response: (data: Handler['data']): Tracker => { | ||
const handlers = this.responses.get(queryMethod) || []; | ||
handlers.push({ match: matcher, data }); | ||
|
||
return this; | ||
}, | ||
responseOnce: (data: Handler['data']): Tracker => { | ||
const handlers = this.responses.get(queryMethod) || []; | ||
handlers.push({ match: matcher, data, once: true }); | ||
|
||
return this; | ||
}, | ||
simulateError: (errorMessage: Handler['errorMessage']): Tracker => { | ||
const handlers = this.responses.get(queryMethod) || []; | ||
handlers.push({ match: matcher, data: null, errorMessage }); | ||
return this; | ||
}, | ||
simulateErrorOnce: (errorMessage: Handler['errorMessage']): Tracker => { | ||
const handlers = this.responses.get(queryMethod) || []; | ||
handlers.push({ match: matcher, data: null, once: true, errorMessage }); | ||
return this; | ||
}, | ||
}; | ||
}; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export const queryMethods = ['select', 'insert', 'update', 'delete'] as const; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import { MockClient } from './MockClient'; | ||
import { Tracker } from './Tracker'; | ||
|
||
export { MockClient } from './MockClient'; | ||
|
||
export function getTracker(): Tracker { | ||
if (!MockClient.tracker) { | ||
throw new Error('Trying to access tracker before knex initialized'); | ||
} | ||
|
||
return MockClient.tracker; | ||
} |
Oops, something went wrong.