Skip to content

Commit

Permalink
chore: initiate async rest test using supertest
Browse files Browse the repository at this point in the history
  • Loading branch information
Ade Yahya Prasetyo committed Mar 17, 2021
1 parent 8c10e05 commit 263cd13
Show file tree
Hide file tree
Showing 15 changed files with 263 additions and 11,257 deletions.
1 change: 0 additions & 1 deletion .cache/.warlock

This file was deleted.

2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ node_modules/
dist/

.autoenv.zsh
yarn-error.log
.cache
68 changes: 68 additions & 0 deletions __tests__/fakerResolver01.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import os from 'os';
import path from 'path';
import fs from 'fs/promises';
import request from 'supertest';
import { Config } from '../src/types/config-combine';
import { runForTest } from '../src/express';

const config: Config = {
rest: {
sources: [
{
name: 'pokeapi',
origin: 'https://pokeapi.co',
transforms: {
'/api/v2/berry/:id': {
get: [
{
field: 'root.name',
resolvers: [
{
faker: 'name.firstName',
},
],
},
],
},
},
},
],
},
};

const homeDir = os.homedir();
const cachePath = path.join(homeDir, '.warlock-cache');

describe('faker resolver 1', () => {
beforeAll(() => {
return Promise.all([fs.rmdir(cachePath, { recursive: true })]);
});

const app = runForTest(config);

it('(MOCKPUBAPI01) should response 200 and cache miss', (done) => {
request(app)
.get('/https://pokeapi.co/api/v2/berry/1')
.expect(200)
.end((err, res) => {
if (err) return done(err);

expect(res.headers['x-warlock-cache']).toBe('MISS');
expect(typeof res?.body?.firmness?.name).toBe('string');
done();
});
});

it('(MOCKPUBAPI02) should response 200 and cache hit', (done) => {
request(app)
.get('/https://pokeapi.co/api/v2/berry/1')
.expect(200)
.end((err, res) => {
if (err) return done(err);

expect(res.headers['x-warlock-cache']).toBe('HIT');
expect(typeof res?.body?.firmness?.name).toBe('string');
done();
});
});
});
70 changes: 70 additions & 0 deletions __tests__/fakerResolver02.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import os from 'os';
import path from 'path';
import fs from 'fs/promises';
import request from 'supertest';
import { Config } from '../src/types/config-combine';
import { runForTest } from '../src/express';

const config: Config = {
rest: {
sources: [
{
name: 'pokeapi',
origin: 'https://pokeapi.co',
transforms: {
'/api/v2/berry/:id': {
get: [
{
field: 'root.name',
resolvers: [
{
faker: 'name.firstName',
},
],
},
],
},
},
},
],
},
};

const homeDir = os.homedir();
const cachePath = path.join(homeDir, '.warlock-cache');

describe('faker resolver 1', () => {
beforeAll(() => {
return Promise.all([fs.rmdir(cachePath, { recursive: true })]);
});

const app = runForTest(config);

it('(MOCKPUBAPI04) should response 200 and cache miss', (done) => {
request(app)
.get('/https://pokeapi.co/api/v2/berry/1')
.expect(200)
.end((err, res) => {
if (err) return done(err);

expect(res.headers['x-warlock-cache']).toBe('MISS');
expect(res?.body?.firmness?.name !== 'cheri').toBe(true);
expect(typeof res?.body?.firmness?.name).toBe('string');
done();
});
});

it('(MOCKPUBAPI05) should response 200 and cache hit', (done) => {
request(app)
.get('/https://pokeapi.co/api/v2/berry/1')
.expect(200)
.end((err, res) => {
if (err) return done(err);

expect(res.headers['x-warlock-cache']).toBe('HIT');
expect(res?.body?.firmness?.name !== 'cheri').toBe(true);
expect(typeof res?.body?.firmness?.name).toBe('string');
done();
});
});
});
8 changes: 6 additions & 2 deletions __tests__/fs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ describe('fs utils buildDirPath with basePath', () => {
});

describe('fs utils createDir', () => {
console.log(process.cwd());
// prerequisite step
const basePath = process.cwd();
const concatBasePathWith = buildDirPath(basePath);
Expand All @@ -40,6 +39,11 @@ describe('fs utils createDir', () => {
const mkdirTest = createDir(dir);
mkdirTest();

expect(E.fold((a: Error) => a.message, a => a)(mkdirTest())).toContain('file already exists');
expect(
E.fold(
(a: Error) => a.message,
(a) => a,
)(mkdirTest()),
).toContain('file already exists');
});
});
3 changes: 2 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ const { compilerOptions } = require('./tsconfig');
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
collectCoverageFrom: ['tests/**/*.{ts,tsx,js,jsx}'],
collectCoverageFrom: ['**/__tests__/**/*.spec.[jt]s?(x)'],
transform: { '.(ts|tsx)$': 'ts-jest/dist' },
transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$'],
testMatch: ['**/__tests__/**/*.spec.[jt]s?(x)'],
globals: {
'ts-jest': {
tsconfig: 'tsconfig.json',
Expand Down
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"build:cjs": "cross-env BABEL_ENV=cjs babel src --extensions '.ts,.tsx' -d dist/cjs --source-maps",
"build_:types": "tsc --emitDeclarationOnly --declaration --declarationDir dist/types",
"test": "concurrently yarn:test:*",
"test:unit": "jest",
"test:unit": "NODE_ENV=test jest",
"test:type": "tsc --noEmit",
"test:lint": "yarn lint src/**/*.ts",
"test:format": "yarn format src/**/*.ts",
Expand Down Expand Up @@ -72,7 +72,8 @@
"sort-keys": "^4.2.0",
"sort-object": "^3.0.3",
"sort-object-keys": "^1.1.3",
"ts-node": "^9.1.1"
"ts-node": "^9.1.1",
"url-pattern": "^1.0.3"
},
"devDependencies": {
"@babel/core": "^7.12.17",
Expand All @@ -92,6 +93,7 @@
"@types/lru-cache": "^5.1.0",
"@types/md5": "^2.3.0",
"@types/node": "^14.14.28",
"@types/supertest": "^2.0.10",
"@warungpintar/warpin-scripts": "*",
"babel-jest": "^26.6.3",
"babel-plugin-inline-json-import": "^0.3.2",
Expand All @@ -109,6 +111,7 @@
"ora": "5.3.0",
"pinst": "2.1.4",
"should": "^13.2.3",
"supertest": "^6.1.3",
"ts-jest": "^26.5.1",
"winston": "3.3.3"
},
Expand Down
6 changes: 3 additions & 3 deletions src/cli/runServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { getConfig } from '../config';
import { fileWatcher } from './watcher';
import { logger } from '../logger';
import { getPatResolvers } from '../utils';
import { PATH_RESOLVER_DIRECTORI } from '../constant';
import { PATH_RESOLVER_DIR } from '../constant';

const runServer = (config: string, port: number) => {
const filePath = path.join(process.cwd(), config ?? '.warlock.yaml');
Expand All @@ -26,7 +26,7 @@ const runServer = (config: string, port: number) => {
minify: true,
platform: 'node',
format: 'cjs',
outfile: path.join(PATH_RESOLVER_DIRECTORI, resolverPath),
outfile: path.join(PATH_RESOLVER_DIR, resolverPath),
});
});
logger.info('building resolvers');
Expand All @@ -43,7 +43,7 @@ const runServer = (config: string, port: number) => {
minify: true,
platform: 'node',
format: 'cjs',
outfile: path.join(PATH_RESOLVER_DIRECTORI, resolverPath),
outfile: path.join(PATH_RESOLVER_DIR, resolverPath),
});
logger.info('restaring server');
})(path.join(process.cwd(), resolverPath));
Expand Down
2 changes: 1 addition & 1 deletion src/constant.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import path from 'path';

export const PATH_RESOLVER_DIRECTORI = path.join(
export const PATH_RESOLVER_DIR = path.join(
process.cwd(),
'node_modules/.warlock-resolvers',
);
Expand Down
5 changes: 5 additions & 0 deletions src/express/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ export const run = ({ port, config }: IRun) => {
});
};

export const runForTest = (config: Config) => {
app.set('config', config);
return app;
};

const cleanup = () => {
console.info('shutdown signal is received');
console.info('will shutdown in 250ms');
Expand Down
9 changes: 7 additions & 2 deletions src/resolvers/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
import path from 'path';
import { flow } from 'fp-ts/function';
import { Request, Response } from 'express';
import { PATH_RESOLVER_DIRECTORI } from '../constant';
import { PATH_RESOLVER_DIR } from '../constant';

const isTestEnv = process.env.NODE_ENV === 'test';

export type Context = {
res: Response;
Expand All @@ -11,7 +13,10 @@ export type Context = {

export const pathResolver = (filePath: string, context: Context) =>
flow((data: any) => {
const functionPath = path.join(PATH_RESOLVER_DIRECTORI, filePath);
const functionPath = path.join(
isTestEnv ? process.cwd() : PATH_RESOLVER_DIR,
filePath,
);
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete require.cache[functionPath];
const mockFunction = require(functionPath);
Expand Down
15 changes: 13 additions & 2 deletions src/utils/resolver.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as O from 'fp-ts/Option';
import { findFirst, reduce } from 'fp-ts/Array';
import UrlPattern from 'url-pattern';
import { Config } from '../types/config-combine';
import {
fakerResolver,
Expand Down Expand Up @@ -54,8 +55,18 @@ export const parseModule = (url: URL) => (config: Module[]) =>
findFirst((module: Module) => module.origin === url.origin)(config);

export const parseModulePathHandler = (url: URL) => (module: Module) => {
if (module.transforms[url.pathname]) {
return O.some(module.transforms[url.pathname]);
const pathHandlerKey = Object.keys(module.transforms).find((item) => {
if (item === url.pathname) return true;

const pattern = new UrlPattern(item);

if (pattern.match(url.pathname)) return true;

return false;
});

if (pathHandlerKey) {
return O.some(module.transforms[pathHandlerKey]);
}

return O.none;
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
],
"include": [
"src",
"__tests__/"
"__tests__/**/*.spec.ts",
"__tests__/fakerResolver01.ts"
],
"exclude": [
"node_modules",
Expand Down
Loading

0 comments on commit 263cd13

Please sign in to comment.