UNPKG

omnipartners

Version:
106 lines (105 loc) 3.52 kB
"use strict"; /* eslint-env mocha */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.describeApi = exports.describeMethod = exports.withMock = exports.withArguments = exports.NOCK_RECORD = exports.REGEX_HASH = void 0; const nock_1 = __importDefault(require("nock")); exports.REGEX_HASH = /[0-9a-z]{40}/i; exports.NOCK_RECORD = !!process.env.NOCK_RECORD; if (exports.NOCK_RECORD) { nock_1.default.recorder.rec(); } afterEach(() => { nock_1.default.cleanAll(); }); function withArguments(data, { shouldThrow = false } = {}) { return (_, _2, descriptor) => { const fn = descriptor.value; descriptor.value = async function () { const api = new this.Api(this.apiConfig); if (this.use) { this.use(api); } const method = this.name; let err = null; let response = null; try { response = await api[method](data); } catch (e) { if (!shouldThrow || !e /* | Error */.isOmnipartnersError) { throw e; } else { err = e; } } return fn({ err, response, }); }; }; } exports.withArguments = withArguments; function withMock({ query, reply, delay, }) { return (_, _2, descriptor) => { const fn = descriptor.value; descriptor.value = async function (...args) { const { httpMethod, httpPath, httpDefaultData, } = this; // tslint:disable-line no-this-assignment const data = { ...httpDefaultData, ...query, }; const tmpMock = (0, nock_1.default)(this.apiConfig.host, { // encodedQueryParams: true })[httpMethod](httpPath); if (delay) { tmpMock.delay(delay); } const mock = tmpMock .query((qs) => { return Object.keys(data).reduce((valid, key) => { if (!valid) { return false; } if (data[key].test) { return data[key].test(qs[key]); } else { return (decodeURIComponent(data[key]) === decodeURIComponent(qs[key])); } }, true); }) .reply(200, reply); const res = await fn.apply(this, args); if (!exports.NOCK_RECORD) { mock.done(); } return res; }; }; } exports.withMock = withMock; function describeMethod(Klass) { describe(`${Klass.name}()`, () => { const methods = Object.getOwnPropertyNames(Klass.prototype); const filterMethod = (method) => method !== "constructor"; methods.filter(filterMethod).forEach((method) => { it(method, () => { const instance = new Klass(); return instance[method](); }); }); }); } exports.describeMethod = describeMethod; function describeApi(api, fn) { describe(`API: ${api}`, fn); } exports.describeApi = describeApi; describe("Test utils", () => { it("works", () => { }); });