Skip to content

Commit

Permalink
Add Jest
Browse files Browse the repository at this point in the history
  • Loading branch information
hsjoberg committed Feb 1, 2021
1 parent 692650e commit cbfb5cd
Show file tree
Hide file tree
Showing 13 changed files with 3,064 additions and 29 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ config/default.json
database.db
src/proto.js
src/proto.d.ts
coverage
.nyc_output
2 changes: 1 addition & 1 deletion config/default.json_TEMPLATE
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"backendConfig": {
"lndNode": "127.0.0.1:9735",
"grpcServer": "127.0.0.1:10009",
"adminMacaroon": "~/.lnd/data/chain/bitcoin/regtest/admin.macaroon",
"cert": "~/.lnd/tls.cert",
"adminMacaroon": "~/.lnd/data/chain/bitcoin/regtest/admin.macaroon",
}
}
11 changes: 11 additions & 0 deletions config/test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"serverHost": "127.0.0.1:8089",
"backend": "lnd",
"env": "test",
"backendConfig": {
"lndNode": "127.0.0.1:9735",
"grpcServer": "127.0.0.1:10009",
"cert": "~/.lnd/tls.cert",
"adminMacaroon": "~/.lnd/data/chain/bitcoin/regtest/admin.macaroon"
}
}
10 changes: 10 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
globals: {
"ts-jest": {
tsconfig: "./tsconfig-tests.json",
},
},
setupFiles: ["./jestSetup.js"],
};
2 changes: 2 additions & 0 deletions jestSetup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
jest.mock("./src/utils/grpc", () => require("./mocks/utils/grpc"));
jest.mock("./src/utils/lnd-api", () => require("./mocks/utils/lnd-api"));
16 changes: 16 additions & 0 deletions mocks/utils/grpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Client } from "@grpc/grpc-js";

export const rpcImpl = jest.fn();

export const getGrpcClients = () => jest.fn();

export const grpcReqSerialize = (args: any) => jest.fn();

export const grpcReqDeserialize = (args: any) => jest.fn();

export const grpcMakeUnaryRequest = <Response = unknown>(
client: Client,
method: string,
argument: Uint8Array,
decoder = (data: Uint8Array) => data as any,
) => jest.fn();
68 changes: 68 additions & 0 deletions mocks/utils/lnd-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { Client } from "@grpc/grpc-js";
import Long from "long";
import { Stream } from "stream";

import { lnrpc } from "../../src/proto";
import { stringToUint8Array } from "../../src/utils/common";

export async function getInfo(lightning: Client) {
const getInfoResponse = lnrpc.GetInfoResponse.create({
identityPubkey: "abc",
});
return getInfoResponse;
}

export async function estimateFee(lightning: Client, amount: Long, targetConf: number) {
const estimateFeeResponse = lnrpc.EstimateFeeResponse.encode({
feeSat: Long.fromValue(10),
feerateSatPerByte: Long.fromValue(100),
});
return estimateFeeResponse;
}

let verifyMessageValidSig = true;
export const __verifyMessageSetValidSig = (valid: boolean) => (verifyMessageValidSig = valid);
export async function verifyMessage(lightning: Client, message: string, signature: string) {
const verifyMessageResponse = lnrpc.VerifyMessageResponse.create({
pubkey: verifyMessageValidSig ? "abcdef12345" : "notvalidsig",
});
return verifyMessageResponse;
}

export async function listPeers(lightning: Client) {
const listPeersReponse = lnrpc.ListPeersResponse.create({
peers: [
{
pubKey: "abcdef123456",
},
],
});
return listPeersReponse;
}

export async function openChannelSync(
lightning: Client,
pubkey: string,
localFundingAmount: Long,
pushSat: Long,
privateChannel: boolean,
spendUnconfirmed: boolean,
) {
const openChannelSyncResponse = lnrpc.ChannelPoint.create({
fundingTxidBytes: stringToUint8Array("abcdef"),
outputIndex: 0,
});
return openChannelSyncResponse;
}

export function htlcInterceptor(router: Client) {
return new Stream();
}

export function subscribeHtlcEvents(router: Client) {
return new Stream();
}

export function subscribeChannelEvents(lightning: Client) {
return new Stream();
}
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"build": "tsc -p tsconfig.json && cp src/proto.js dist",
"start": "yarn build && node dist/server.js",
"watch": "concurrently \"tsc -p tsconfig.json -w\" \"nodemon -w dist dist/server.js\"",
"proto": "pbjs --force-long -t static-module -o src/proto.js proto/rpc.proto proto/router.proto && pbts -o src/proto.d.ts src/proto.js"
"proto": "pbjs --force-long -t static-module -o src/proto.js proto/rpc.proto proto/router.proto && pbts -o src/proto.d.ts src/proto.js",
"test": "jest tests",
"test:coverage": "jest --coverage tests"
},
"version": "1.0.0",
"main": "index.js",
Expand All @@ -22,13 +24,15 @@
"fastify-cors": "5.2.0",
"fastify-websocket": "2.1.0",
"grpc": "1.24.4",
"jest": "^26.6.3",
"nodemon": "^2.0.7",
"protobufjs": "6.10.2",
"sqlite": "^4.0.19",
"sqlite3": "^5.0.1",
"typescript": "4.1.3"
},
"devDependencies": {
"@types/node": "14.14.22"
"@types/node": "14.14.22",
"ts-jest": "^26.5.0"
}
}
16 changes: 16 additions & 0 deletions tests/app.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import build from "../src/app";
const app = build();

test('requests the "/" route', async (done) => {
const response = await app.inject({
method: "GET",
url: "/",
});
expect(response.statusCode).toBe(200);

done();
});

afterAll(() => {
app.close();
});
43 changes: 43 additions & 0 deletions tests/services/ondemand-channel/api/check-status.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { ICheckStatusRequest } from "../../../..//src/services/ondemand-channel/api/check-status";
import build from "../../../../src/app";
const app = build();

describe("/ondemand-channel/check-status", () => {
test("works under normal conditions", async () => {
const response = await app.inject({
url: "/ondemand-channel/check-status",
method: "POST",
headers: {
"Content-Type": "text/plain",
},
payload: JSON.stringify({
pubkey: "abcdef12345",
signature: "sig123",
} as ICheckStatusRequest),
});

expect(response.statusCode).toBe(200);
});

test("fails on erroneous signature", async () => {
require("../../../../src/utils/lnd-api").__verifyMessageSetValidSig(false);
const response = await app.inject({
url: "/ondemand-channel/check-status",
method: "POST",
headers: {
"Content-Type": "text/plain",
},
payload: JSON.stringify({
pubkey: "abcdef12345",
signature: "badsig",
} as ICheckStatusRequest),
});

expect(response.statusCode).toBe(400);
require("../../../../src/utils/lnd-api").__verifyMessageSetValidSig(true);
});
});

afterAll(() => {
app.close();
});
69 changes: 69 additions & 0 deletions tsconfig-tests.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */

/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es2017" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "CommonJS" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"lib": [] /* Specify library files to be included in the compilation. */,
"allowJs": true /* Allow javascript files to be compiled. */,
"checkJs": false /* Report errors in .js files. */,
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"baseUrl": "." /* Base directory to resolve non-absolute module names. */,
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
"rootDirs": [] /* List of root folders whose combined content represents the structure of the project at runtime. */,
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,5 @@
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"exclude": ["tests", "./*.js"]
"exclude": ["dist", "tests", "mocks", "./*.js"]
}
Loading

0 comments on commit cbfb5cd

Please sign in to comment.