I have an external/outward facing class. It contains input-validation code for instances where the library is imported into a JS environment (read: an environment that does not support type checking).
I am attempting to write unit tests specific to that validation code.
// function-token.ts;
// ...
export default class FunctionToken extends Token {
constructor(token: IFunctionToken) {
if (token == null) {
throw new Error('token must be specified');
}
// ...
}
}
Currently when I attempt to write a jestjs test for the validation code, the check fails due to typings:
// function-token.spec.ts
import FunctionToken from 'function-token';
test('throws an error when token is nullish', function () {
// Expected 1 arguments, but got 0 - An argument for 'token' was not provided
expect(() => new FunctionToken()).toThrow();
// Argument of [undefined|null] is not assignable to IFunctionToken
expect(() => new FunctionToken(undefined)).toThrow();
expect(() => new FunctionToken(null)).toThrow();
});
How do I go about writing a test to subvert the type check with jestjs ts-jest?
Note: Changing the underlying class's typing does not make sense as the validation is specific to cases where there is no type checking or enforcement.
CodePudding user response:
Not sure how you'll get the parameterless call, but I think this is redundant because it defaults to undefined anyway. By casting the arguments to any
you can bypass the parameter typings.
expect(() => new FunctionToken(undefined as any)).toThrow();
expect(() => new FunctionToken(null as any)).toThrow();
Alternativly you could just add // @ts-nocheck
in testfiles concerning guard clauses.