Skip to content

Commit

Permalink
patch: use invariant utility
Browse files Browse the repository at this point in the history
  • Loading branch information
ealush committed Mar 7, 2022
1 parent 6a4ed2c commit e13b558
Show file tree
Hide file tree
Showing 24 changed files with 118 additions and 183 deletions.
11 changes: 5 additions & 6 deletions packages/context/src/context.ts
@@ -1,7 +1,7 @@
import assign from 'assign';
import defaultTo from 'defaultTo';
import invariant from 'invariant';
import optionalFunctionValue from 'optionalFunctionValue';
import throwError from 'throwError';

// eslint-disable-next-line max-lines-per-function
export function createContext<T extends Record<string, unknown>>(
Expand All @@ -22,12 +22,11 @@ export function createContext<T extends Record<string, unknown>>(
};

function useX(errorMessage?: string): T {
return (
(storage.ctx as T) ??
throwError(
defaultTo(errorMessage, 'Context was used after it was closed')
)
invariant(
storage.ctx,
defaultTo(errorMessage, 'Context was used after it was closed')
);
return storage.ctx as T;
}

function run<R>(ctxRef: Partial<T>, fn: (context: T) => R): R {
Expand Down
14 changes: 3 additions & 11 deletions packages/n4s/src/exports/compose.ts
@@ -1,9 +1,8 @@
import invariant from 'invariant';
import mapFirst from 'mapFirst';
import throwError from 'throwError';
import { ctx } from 'n4s';

import type { TComposeResult, TLazyRuleRunners } from 'genEnforceLazy';
import { isEmpty } from 'isEmpty';
import { ctx } from 'n4s';
import { defaultToPassing, TRuleDetailedResult } from 'ruleReturn';
import runLazyRule from 'runLazyRule';

Expand All @@ -16,14 +15,7 @@ export default function compose(
(value: any) => {
const res = run(value);

if (!res.pass) {
if (isEmpty(res.message)) {
throwError();
} else {
// Explicitly throw a string so that vest.test can pick it up as the validation error message
throw res.message;
}
}
invariant(res.pass, new String(res.message));
},
{
run,
Expand Down
11 changes: 5 additions & 6 deletions packages/n4s/src/lib/transformResult.ts
@@ -1,6 +1,6 @@
import invariant from 'invariant';
import { isBoolean } from 'isBooleanValue';
import optionalFunctionValue from 'optionalFunctionValue';
import throwError from 'throwError';

import ruleReturn, { TRuleReturn, TRuleDetailedResult } from 'ruleReturn';
import type { TRuleValue, TArgs } from 'runtimeRules';
Expand Down Expand Up @@ -29,9 +29,8 @@ export function transformResult(

function validateResult(result: TRuleReturn): void {
// if result is boolean, or if result.pass is boolean
if (isBoolean(result) || (result && isBoolean(result.pass))) {
return;
}

throwError('Incorrect return value for rule: ' + JSON.stringify(result));
invariant(
isBoolean(result) || (result && isBoolean(result.pass)),
'Incorrect return value for rule: ' + JSON.stringify(result)
);
}
19 changes: 8 additions & 11 deletions packages/n4s/src/runtime/enforceEager.ts
@@ -1,4 +1,4 @@
import throwError from 'throwError';
import invariant from 'invariant';

import eachEnforceRule from 'eachEnforceRule';
import { ctx } from 'enforceContext';
Expand Down Expand Up @@ -45,16 +45,13 @@ export default function enforceEager(value: TRuleValue): IRules {
...args
);

if (!transformedResult.pass) {
if (isEmpty(transformedResult.message)) {
throwError(
`enforce/${ruleName} failed with ${JSON.stringify(value)}`
);
} else {
// Explicitly throw a string so that vest.test can pick it up as the validation error message
throw transformedResult.message;
}
}
invariant(
transformedResult.pass,
isEmpty(transformedResult.message)
? `enforce/${ruleName} failed with ${JSON.stringify(value)}`
: new String(transformedResult.message)
);

return target;
};
}
Expand Down
41 changes: 0 additions & 41 deletions packages/shared/src/__tests__/throwError.test.ts

This file was deleted.

19 changes: 19 additions & 0 deletions packages/shared/src/invariant.ts
@@ -0,0 +1,19 @@
import optionalFunctionValue from 'optionalFunctionValue';
import { TStringable } from 'utilityTypes';

export default function invariant(
condition: any,
// eslint-disable-next-line @typescript-eslint/ban-types
message?: String | TStringable
): asserts condition {
if (condition) {
return;
}

// If message is a string object (rather than string literal)
// Throw the value directly as a string
// Alternatively, throw an error with the message
throw message instanceof String
? message.valueOf()
: new Error(message ? optionalFunctionValue(message) : message);
}
21 changes: 2 additions & 19 deletions packages/shared/src/throwError.ts
@@ -1,22 +1,5 @@
import defaultTo from 'defaultTo';

/**
* Throws a timed out error.
*/
export default function throwError(
devMessage?: string,
productionMessage?: string
): never {
throw new Error(
__DEV__ ? devMessage : defaultTo(productionMessage, devMessage)
);
}

export function throwErrorDeferred(
devMessage?: string,
productionMessage?: string
): void {
export function deferThrow(message?: string): void {
setTimeout(() => {
throwError(devMessage, productionMessage);
throw new Error(message);
}, 0);
}
14 changes: 7 additions & 7 deletions packages/vest/src/__tests__/isolate.test.ts
Expand Up @@ -5,12 +5,12 @@ import { IsolateTypes } from 'IsolateTypes';
describe('isolate', () => {
let firstRun = true;
let vest, isolate, skipWhen, dummyTest;
let throwErrorDeferred;
let deferThrow;

beforeEach(() => {
firstRun = true;
const mock = mockThrowError();
throwErrorDeferred = mock.throwErrorDeferred;
deferThrow = mock.deferThrow;
vest = mock.vest;
skipWhen = vest.skipWhen;
isolate = require('isolate').isolate;
Expand Down Expand Up @@ -240,10 +240,10 @@ describe('isolate', () => {
});

suite();
expect(throwErrorDeferred).toHaveBeenCalledTimes(0);
expect(deferThrow).toHaveBeenCalledTimes(0);
suite();
expect(throwErrorDeferred).toHaveBeenCalledTimes(1);
expect(throwErrorDeferred).toHaveBeenCalledWith(
expect(deferThrow).toHaveBeenCalledTimes(1);
expect(deferThrow).toHaveBeenCalledWith(
expect.stringContaining(
'Vest Critical Error: Tests called in different order than previous run'
)
Expand All @@ -258,9 +258,9 @@ describe('isolate', () => {
});

suite();
expect(throwErrorDeferred).toHaveBeenCalledTimes(0);
expect(deferThrow).toHaveBeenCalledTimes(0);
suite();
expect(throwErrorDeferred).toHaveBeenCalledTimes(0);
expect(deferThrow).toHaveBeenCalledTimes(0);
});
});
});
Expand Down
6 changes: 2 additions & 4 deletions packages/vest/src/core/isolate/isolates/each.ts
@@ -1,5 +1,5 @@
import invariant from 'invariant';
import isFunction from 'isFunction';
import throwError from 'throwError';

import { IsolateTypes } from 'IsolateTypes';
import { isolate } from 'isolate';
Expand All @@ -21,9 +21,7 @@ export default function each<T>(
list: T[],
callback: (arg: T, index: number) => void
): void {
if (!isFunction(callback)) {
throwError('each callback must be a function');
}
invariant(isFunction(callback), 'each callback must be a function');

isolate({ type: IsolateTypes.EACH }, () => {
list.forEach((arg, index) => {
Expand Down
14 changes: 5 additions & 9 deletions packages/vest/src/core/isolate/isolates/group.ts
@@ -1,6 +1,6 @@
import invariant from 'invariant';
import isFunction from 'isFunction';
import { isStringValue } from 'isStringValue';
import throwError from 'throwError';

import { IsolateTypes } from 'IsolateTypes';
import context from 'ctx';
Expand All @@ -16,20 +16,16 @@ import { isolate } from 'isolate';
* });
*/
export default function group(groupName: string, tests: () => void): void {
if (!isStringValue(groupName)) {
throwGroupError('name must be a string');
}
invariant(isStringValue(groupName), groupErrorMsg('name must be a string'));

if (!isFunction(tests)) {
throwGroupError('callback must be a function');
}
invariant(isFunction(tests), groupErrorMsg('callback must be a function'));

// Running with the context applied
isolate({ type: IsolateTypes.GROUP }, () => {
context.run({ groupName }, tests);
});
}

function throwGroupError(error: string) {
throwError(`Wrong arguments passed to group. Group ${error}.`);
function groupErrorMsg(error: string) {
return `Wrong arguments passed to group. Group ${error}.`;
}
9 changes: 5 additions & 4 deletions packages/vest/src/core/suite/create.ts
@@ -1,7 +1,7 @@
import assign from 'assign';
import genId from 'genId';
import invariant from 'invariant';
import isFunction from 'isFunction';
import throwError from 'throwError';
import { createState } from 'vast';

import { IsolateTypes } from 'IsolateTypes';
Expand Down Expand Up @@ -47,9 +47,10 @@ function create<T extends CB>(
): SuiteReturnType<T> {
const [suiteCallback, suiteName] = args.reverse() as [T, string];

if (!isFunction(suiteCallback)) {
throwError('vest.create: Expected callback to be a function.');
}
invariant(
isFunction(suiteCallback),
'vest.create: Expected callback to be a function.'
);

// Event bus initialization
const bus = initBus();
Expand Down
@@ -1,4 +1,4 @@
import throwError from 'throwError';
import invariant from 'invariant';

import { Severity } from 'Severity';
import collectFailureMessages from 'collectFailureMessages';
Expand Down Expand Up @@ -41,13 +41,12 @@ function getByGroup(
group: string,
fieldName?: string
): Record<string, string[]> {
if (!group) {
throwError(
`get${severityKey[0].toUpperCase()}${severityKey.slice(
1
)}ByGroup requires a group name. Received \`${group}\` instead.`
);
}
invariant(
group,
`get${severityKey[0].toUpperCase()}${severityKey.slice(
1
)}ByGroup requires a group name. Received \`${group}\` instead.`
);
const testObjects = useTestsFlat();
return collectFailureMessages(severityKey, testObjects, {
group,
Expand Down
6 changes: 3 additions & 3 deletions packages/vest/src/core/test/__tests__/key.test.ts
Expand Up @@ -147,11 +147,11 @@ describe('key', () => {
});

describe('When the same key is encountered twice', () => {
let throwErrorDeferred, vest;
let deferThrow, vest;
beforeEach(() => {
const mock = mockThrowError();

throwErrorDeferred = mock.throwErrorDeferred;
deferThrow = mock.deferThrow;
vest = mock.vest;
});

Expand All @@ -166,7 +166,7 @@ describe('key', () => {
vest.test('field2', () => false, 'key_1');
});
suite();
expect(throwErrorDeferred).toHaveBeenCalledWith(
expect(deferThrow).toHaveBeenCalledWith(
`Encountered the same test key "key_1" twice. This may lead to tests overriding each other's results, or to tests being unexpectedly omitted.`
);
});
Expand Down

1 comment on commit e13b558

@vercel
Copy link

@vercel vercel bot commented on e13b558 Mar 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

vest-next – ./website

vest-next-git-latest-ealush.vercel.app
vest-next.vercel.app
vest-next-ealush.vercel.app
vest-website.vercel.app

Please sign in to comment.