@jest/globals#describe TypeScript Examples
The following examples show how to use
@jest/globals#describe.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.test.ts From setup-buildx-action with Apache License 2.0 | 7 votes |
describe('isValidUrl', () => {
test.each([
['https://github.com/docker/buildx.git', true],
['https://github.com/docker/buildx.git#refs/pull/648/head', true],
['v0.4.1', false]
])('given %p', async (url, expected) => {
expect(util.isValidUrl(url)).toEqual(expected);
});
});
Example #2
Source File: number.spec.ts From ya-webadb with MIT License | 6 votes |
function testDeserialize(type: NumberFieldType) {
if (type.size === 1) {
if (type.signed) {
testEndian(type, 2 ** (type.size * 8) / -2, 2 ** (type.size * 8) / 2 - 1, false);
} else {
testEndian(type, 0, 2 ** (type.size * 8) - 1, false);
}
} else {
if (type.signed) {
describe('big endian', () => {
testEndian(type, 2 ** (type.size * 8) / -2, 2 ** (type.size * 8) / 2 - 1, false);
});
describe('little endian', () => {
testEndian(type, 2 ** (type.size * 8) / -2, 2 ** (type.size * 8) / 2 - 1, true);
});
} else {
describe('big endian', () => {
testEndian(type, 0, 2 ** (type.size * 8) - 1, false);
});
describe('little endian', () => {
testEndian(type, 0, 2 ** (type.size * 8) - 1, true);
});
}
}
}
Example #3
Source File: communication.test.ts From slice-machine with Apache License 2.0 | 6 votes |
describe("maybeParseRepoData", () => {
test("with repos as a string", () => {
const repos = JSON.stringify({
foo: { role: Roles.ADMIN, dbid: "foo" },
});
const result = communication.maybeParseRepoData(repos);
expect(result.foo).toBeDefined();
expect(result.foo.role).toEqual(Roles.ADMIN);
});
});
Example #4
Source File: fixed-length.spec.ts From ya-webadb with MIT License | 6 votes |
describe("Types", () => {
describe("FixedLengthArrayBufferLikeFieldDefinition", () => {
describe("#getSize", () => {
it("should return size in its options", () => {
const definition = new FixedLengthBufferLikeFieldDefinition(
Uint8ArrayBufferFieldSubType.Instance,
{ length: 10 },
);
expect(definition.getSize()).toBe(10);
});
});
});
});
Example #5
Source File: communication.test.ts From slice-machine with Apache License 2.0 | 6 votes |
describe("communication.getUserPrfile", () => {
test("when called with cookies it should fetch the user profile form 'https://user.internal-prismic.io/profile`", async () => {
const token = "biscuits";
const cookie = `prismic-auth=${token}`;
nock("https://user.internal-prismic.io")
.matchHeader("Authorization", `Bearer ${token}`)
.get("/profile")
.reply(200, {
userId: "1234",
shortId: "12",
intercomHash: "intercomHash",
email: "[email protected]",
firstName: "Bat",
lastName: "Man",
});
const result = await communication.getUserProfile(cookie);
expect(result.shortId).toEqual("12");
});
test("when given data that is not valid it should throw an error", async () => {
const token = "biscuits";
const cookie = `prismic-auth=${token}`;
nock("https://user.internal-prismic.io")
.matchHeader("Authorization", `Bearer ${token}`)
.get("/profile")
.reply(200, {});
await expect(() =>
communication.getUserProfile(cookie)
).rejects.toThrowError("Can't parse user profile");
});
});
Example #6
Source File: checksums.test.ts From wrapper-validation-action with MIT License | 6 votes |
describe('retry', () => {
afterEach(() => {
nock.cleanAll()
})
describe('for /versions/all API', () => {
test('retry three times', async () => {
nock('https://services.gradle.org', {allowUnmocked: true})
.get('/versions/all')
.times(3)
.replyWithError({
message: 'connect ECONNREFUSED 104.18.191.9:443',
code: 'ECONNREFUSED'
})
const validChecksums = await checksums.fetchValidChecksums(false)
expect(validChecksums.length).toBeGreaterThan(10)
nock.isDone()
})
})
})
Example #7
Source File: QueryBuilder_LambdaProcessingRoundtrip.test.ts From legend-studio with Apache License 2.0 | 6 votes |
describe(unitTest('Lambda processing roundtrip test'), () => {
test.each(cases)(
'%s',
async (
testName: RoundtripTestCase[0],
context: RoundtripTestCase[1],
lambdaJson: RoundtripTestCase[2],
) => {
const { entities } = context;
const graphManagerState = TEST__getTestGraphManagerState(pluginManager);
await TEST__buildGraphWithEntities(graphManagerState, entities);
// roundtrip check
const lambda = graphManagerState.graphManager.buildValueSpecification(
lambdaJson,
graphManagerState.graph,
);
const _lambdaJson =
graphManagerState.graphManager.serializeRawValueSpecification(
graphManagerState.graphManager.buildRawValueSpecification(
lambda,
graphManagerState.graph,
),
);
expect(_lambdaJson).toEqual(lambdaJson);
},
);
});
Example #8
Source File: get-default.spec.ts From leapp with Mozilla Public License 2.0 | 6 votes |
describe("GetDefaultRegion", () => {
test("run", async () => {
const cliProviderService = { regionsService: { getDefaultAwsRegion: () => "defaultRegion" } } as any;
const command = new GetDefaultRegion([], {} as any);
(command as any).cliProviderService = cliProviderService;
command.log = jest.fn();
await command.run();
expect(command.log).toHaveBeenCalledWith("defaultRegion");
});
});
Example #9
Source File: definition.spec.ts From ya-webadb with MIT License | 6 votes |
describe('StructFieldDefinition', () => {
describe('.constructor', () => {
it('should save the `options` parameter', () => {
class MockFieldDefinition extends StructFieldDefinition<number>{
public constructor(options: number) {
super(options);
}
public getSize(): number {
throw new Error('Method not implemented.');
}
public create(options: Readonly<StructOptions>, struct: StructValue, value: unknown): StructFieldValue<this> {
throw new Error('Method not implemented.');
}
public override deserialize(
options: Readonly<StructOptions>,
stream: StructDeserializeStream,
struct: StructValue,
): StructFieldValue<this>;
public override deserialize(
options: Readonly<StructOptions>,
stream: StructAsyncDeserializeStream,
struct: StructValue,
): Promise<StructFieldValue<this>>;
public deserialize(
options: Readonly<StructOptions>,
stream: StructDeserializeStream | StructAsyncDeserializeStream,
struct: StructValue
): ValueOrPromise<StructFieldValue<this>> {
throw new Error('Method not implemented.');
}
}
expect(new MockFieldDefinition(42)).toHaveProperty('options', 42);
});
});
});
Example #10
Source File: QueryBuilder_BuildLambdaFailure.test.tsx From legend-studio with Apache License 2.0 | 6 votes |
describe(
integrationTest(
'Query builder lambda processer should properly handle failure',
),
() => {
test.each(cases)(
'%s',
async (
testName: TestCase[0],
context: TestCase[1],
lambdaJson: TestCase[2],
errorMessage: TestCase[3],
) => {
const { entities } = context;
const pluginManager = LegendQueryPluginManager.create();
pluginManager.usePresets([new Query_GraphPreset()]).install();
const applicationStore = TEST__getTestApplicationStore(
TEST__getTestQueryConfig(),
LegendQueryPluginManager.create(),
);
const graphManagerState = TEST__getTestGraphManagerState(pluginManager);
await TEST__buildGraphWithEntities(graphManagerState, entities);
const queryBuilderState = new QueryBuilderState(
applicationStore,
graphManagerState,
new StandardQueryBuilderMode(),
);
expect(() =>
queryBuilderState.buildStateFromRawLambda(
create_RawLambda(lambdaJson.parameters, lambdaJson.body),
),
).toThrowError(errorMessage);
},
);
},
);
Example #11
Source File: choose-or-create-repo.test.ts From slice-machine with Apache License 2.0 | 6 votes |
describe("maybeStickTheRepoToTheTopOfTheList", () => {
test("when repo name is not given it should return the prompts in order", () => {
const prompts: RepoPrompt[] = [
{ name: "a", value: "a" },
{ name: "b", value: "b" },
{ name: "c", value: "c", disabled: "c" },
];
const start = { name: CREATE_REPO, value: CREATE_REPO };
const result = prompts.reduce(maybeStickTheRepoToTheTopOfTheList(), [
start,
]);
const [top, a, b, c] = result;
expect(top).toBe(start);
expect([a, b, c]).toEqual(prompts);
});
test("when no repo name is given and it apears in the prompts it should be first", () => {
const prompts: RepoPrompt[] = [
{ name: "a", value: "a" },
{ name: "b", value: "b" },
{ name: "c", value: "c", disabled: "c" },
];
const start = { name: CREATE_REPO, value: CREATE_REPO };
const result = prompts.reduce(maybeStickTheRepoToTheTopOfTheList("b"), [
start,
]);
const [first, second] = result;
expect(first).toBe(prompts[1]);
expect(second).toBe(start);
});
});
Example #12
Source File: V1_ValueSpecificationBuilder.test.ts From legend-studio with Apache License 2.0 | 6 votes |
describe(unitTest('Lambda processing roundtrip test'), () => {
test.each(cases)(
'%s',
async (
testName: RoundtripTestCase[0],
context: RoundtripTestCase[1],
lambdaJson: RoundtripTestCase[2],
result: RoundtripTestCase[3],
) => {
const { entities } = context;
const { errorMessage } = result;
const graph = new PureModel(new CoreModel([]), new SystemModel([]), []);
// setup
const graphManager = getGraphManager(
new TEST__GraphPluginManager(),
new Log(),
);
await graphManager.buildGraph(graph, entities, ActionState.create());
const fn = (): void => {
graphManager.buildValueSpecification(lambdaJson, graph);
};
if (errorMessage) {
expect(fn).toThrow(errorMessage);
} else {
fn();
}
},
);
});
Example #13
Source File: choose-or-create-repo.test.ts From slice-machine with Apache License 2.0 | 6 votes |
describe("makeReposPretty", () => {
test("unauthorized role", () => {
const base = "https://prismic.io";
const result = makeReposPretty(base)({
name: "foo-bar",
domain: "domain",
role: Models.Roles.WRITER,
});
expect(result.name).toContain("domain.prismic.io");
expect(result.name).toContain("foo-bar");
expect(result.value).toBe("domain");
expect(result.disabled).toContain("Unauthorized");
});
test("authorized role", () => {
const base = "https://prismic.io";
const result = makeReposPretty(base)({
name: "foo-bar",
domain: "domain",
role: Models.Roles.OWNER,
});
expect(result.name).toContain("domain.prismic.io");
expect(result.name).toContain("foo-bar");
expect(result.value).toBe("domain");
expect(result.disabled).toBeUndefined();
});
});
Example #14
Source File: PatternValidator.test.ts From ui-schema with MIT License | 6 votes |
describe('validatePattern', () => {
test.each([
['string', 'blabla', '^[bla]*$', true],
['string', 'wawawa', '^[bla]*$', false],
['string', 'wawawa', undefined, true],
[['string'], 'wawawa', undefined, true],
[['string'], 'wawawa', '^[bla]*$', false],
[['integer', 'string'], 'wawawa', '^[bla]*$', false],
[['integer', 'string'], 122, '^[bla]*$', true],
['array', [], '^[bla]*$', true],
['array', [], undefined, true],
])('validatePattern(%j, %j, %j): %j', (type: SchemaTypesType, value: any, pattern: string | undefined, expected: boolean) => {
expect(validatePattern(type, value, pattern)).toBe(expected)
})
})
Example #15
Source File: ImportResolutionRoundtrip.test.ts From legend-studio with Apache License 2.0 | 6 votes |
describe(
unitTest('File generation specification import resolution roundtrip'),
() => {
test.each([
['Simple specification', TEST_DATA__FileGenerationRoundtrip],
[
'Specification with package same as system element',
TEST_DATA__FileGenerationWithPackageSameAsSystemElement,
],
])('%s', async (testName, entities) => {
await TEST__checkBuildingElementsRoundtrip(entities);
});
},
);
Example #16
Source File: cli-open-web-console-service.spec.ts From leapp with Mozilla Public License 2.0 | 6 votes |
describe("CliOpenWebConsoleService", () => {
test("openExternalUrl", async () => {
const mockOpenFunction = jest.fn();
jest.mock("open", () => mockOpenFunction);
const { CliOpenWebConsoleService: serviceClass } = await import("./cli-open-web-console-service");
const cliOpenWebConsoleService = new serviceClass();
const url = "http://www.url.com";
await cliOpenWebConsoleService.openExternalUrl(url);
expect(mockOpenFunction).toHaveBeenCalledWith(url);
});
});
Example #17
Source File: ImportResolutionRoundtrip.test.ts From legend-studio with Apache License 2.0 | 6 votes |
describe(unitTest('Flat-data import resolution roundtrip'), () => {
test.each([
// TODO: import resolution for included stores?
['Simple flat-data store', TEST_DATA__FlatDataRoundtrip],
['Complex flat-data store', TEST_DATA__FlatDataRoundtrip2],
['Flat-data mapping', TEST_DATA__FlatDataMappingRoundtrip],
['Flat-data embedded mapping', TEST_DATA__EmbeddedFlatDataMappingRoundtrip],
['Flat-data connection', TEST_DATA__FlatDataConnectionRoundtrip],
[
'Flat-data mapping test input data',
TEST_DATA__FlatDataInputDataRoundtrip,
],
])('%s', async (testName, entities) => {
await TEST__checkBuildingElementsRoundtrip(entities);
});
});
Example #18
Source File: roles.test.ts From slice-machine with Apache License 2.0 | 6 votes |
describe("canUpdateCutsomTypes", () => {
test("should return true only if role is owner or admin", () => {
Object.values(Roles).forEach((role) => {
const result = canUpdateCustomTypes(role);
const wanted =
role === Roles.ADMIN ||
role === Roles.OWNER ||
role === Roles.SUPERUSER;
return expect(result).toBe(wanted);
});
});
});
Example #19
Source File: ImportResolutionRoundtrip.test.ts From legend-studio with Apache License 2.0 | 6 votes |
describe(unitTest('Connection import resolution roundtrip'), () => {
test.each([
['Simple connection', testConnectionRoundtrip],
['Model chain connection', testModelChainConnectionRoundtrip],
// TODO test post processor
])('%s', async (testName, entities) => {
await TEST__checkBuildingElementsRoundtrip(entities);
});
});
Example #20
Source File: PluginSimpleStack.test.tsx From ui-schema with MIT License | 6 votes |
describe('PluginSimpleStack', () => {
it('PluginSimpleStack', async () => {
const {queryByText} = render(
// ts-@ignore
<PluginSimpleStack
// ts-@ignore
handled
// ts-@ignore
widgets={{
WidgetRenderer: WidgetRenderer,
types: {
// @ts-ignore
string: ({valid, handled}: { valid?: boolean, handled?: boolean }) =>
valid === true && handled === true ? 'is-valid' : 'is-invalid',
},
pluginSimpleStack: [{handle: () => ({valid: true})}],
pluginStack: [],
}}
schema={createOrderedMap({type: 'string'})}
/>
)
expect(queryByText('is-valid') !== null).toBeTruthy()
})
})
Example #21
Source File: log-service.spec.ts From leapp with Mozilla Public License 2.0 | 6 votes |
describe("LogService", () => {
test("log", () => {
const logMessages = [];
const toasts = [];
const nativeLogger: ILogger = {
log: (message: string, level: LogLevel) => {
logMessages.push({ message, level });
},
show: (message: string, level: LogLevel) => {
toasts.push({ message, level });
},
};
const logService = new LogService(nativeLogger);
logService.log(new LoggedEntry("[String] Error: message1\\n at Object.", "context1", LogLevel.info));
logService.log(new LoggedEntry("[Number] stack2", 12, LogLevel.warn, true, "stack2"));
logService.log(new LoggedException("[Date] stack3", new Date(), LogLevel.error, undefined, "stack3"));
expect(logMessages[0].level).toBe(LogLevel.info);
expect(logMessages[0].message.startsWith("[String] Error")).toBe(true);
expect(logMessages[1].level).toBe(LogLevel.warn);
expect(logMessages[1].message).toBe("[Number] stack2");
expect(logMessages[2].level).toBe(LogLevel.error);
expect(logMessages[2].message).toBe("[Date] stack3");
expect(toasts).toEqual([
{ level: 2, message: "[Number] stack2" },
{ level: 3, message: "[Date] stack3" },
]);
});
});
Example #22
Source File: resolvePointer.test.ts From ui-schema with MIT License | 6 votes |
describe('JSONPointer', () => {
test.each(testCases)(
'resolvePointer() %j',
(testData) => {
expect(
resolvePointer(testData.pointer, fromJS(testData.data))
).toBe(testData.value)
}
)
})
Example #23
Source File: ImportResolutionRoundtrip.test.ts From legend-studio with Apache License 2.0 | 6 votes |
describe(unitTest('Domain import resolution roundtrip'), () => {
test.each([
['Class', TEST_DATA__ClassRoundtrip],
['Class with complex constraint', TEST_DATA__ClassWithComplexConstraint],
['Enumeration', TEST_DATA__EnumerationRoundtrip],
['Association', TEST_DATA__AssociationRoundtrip],
['Function', TEST_DATA__FunctionRoundtrip],
['Measure', TEST_DATA__MeasureRoundtrip],
])('%s', async (testName, entities) => {
await TEST__checkBuildingElementsRoundtrip(entities);
});
});
Example #24
Source File: retro-compatibility-service.spec.ts From leapp with Mozilla Public License 2.0 | 6 votes |
describe("RetroCompatibilityService", () => {
test("Should exists when created", () => {
const fileService = {};
const keychainService = {};
const repository = {};
const behaviouralSubjectService = {};
const appName = "test";
const lockPath = "";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
expect(new RetroCompatibilityService(fileService, keychainService, repository, behaviouralSubjectService, appName, lockPath)).not.toBe(undefined);
});
});
Example #25
Source File: ExecutionPlanRountrip.test.ts From legend-studio with Apache License 2.0 | 6 votes |
describe(unitTest('Execution plan processing roundtrip test'), () => {
test.each(cases)(
'%s',
async (
testName: RoundtripTestCase[0],
context: RoundtripTestCase[1],
executionPlanJson: RoundtripTestCase[2],
) => {
const { entities } = context;
// setup
const graphManagerState = TEST__getTestGraphManagerState();
await TEST__buildGraphWithEntities(graphManagerState, entities);
// roundtrip check
const executionPlan = graphManagerState.graphManager.buildExecutionPlan(
executionPlanJson,
graphManagerState.graph,
);
const _executionPlanJson =
graphManagerState.graphManager.serializeExecutionPlan(executionPlan);
expect(_executionPlanJson).toEqual(executionPlanJson);
},
);
});
Example #26
Source File: aws-sso-role-service.spec.ts From leapp with Mozilla Public License 2.0 | 6 votes |
describe("AwsSsoRoleService", () => {
test("getAccountNumberFromCallerIdentity", async () => {
const session = {
type: SessionType.awsSsoRole,
roleArn: "abcdefghijklmnopqrstuvwxyz/12345",
} as any;
const awsSsoRoleService = new AwsSsoRoleService(null, null, null, null, null, null, { appendListener: jest.fn(() => {}) } as any);
const accountNumber = await awsSsoRoleService.getAccountNumberFromCallerIdentity(session);
expect(accountNumber).toBe("nopqrstuvwxy");
});
test("getAccountNumberFromCallerIdentity - error", async () => {
const session = {};
const awsSsoRoleService = new AwsSsoRoleService(null, null, null, null, null, null, { appendListener: jest.fn(() => {}) } as any);
await expect(() => awsSsoRoleService.getAccountNumberFromCallerIdentity(session as AwsSsoRoleSession)).rejects.toThrow(
new Error("AWS SSO Role Session required")
);
});
});
Example #27
Source File: convertStringToNumber.test.tsx From ui-schema with MIT License | 6 votes |
describe('convertStringToNumber', () => {
it('convertStringToNumber', async () => {
console.error = jest.fn()
expect(convertStringToNumber('10', 'number')).toBe(10)
expect(convertStringToNumber('010', 'number')).toBe(10)
expect(convertStringToNumber('0', 'number')).toBe(0)
expect(convertStringToNumber(0, 'number')).toBe(0)
expect(convertStringToNumber('0.01', 'number')).toBe(0.01)
expect(convertStringToNumber('0.00001', 'number')).toBe(0.00001)
expect(convertStringToNumber(0.458, 'number')).toBe(0.458)
expect(convertStringToNumber('10', 'integer')).toBe(10)
expect(convertStringToNumber('010', 'integer')).toBe(10)
expect(convertStringToNumber('010000000', 'integer')).toBe(10000000)
expect(convertStringToNumber('0', 'integer')).toBe(0)
expect(convertStringToNumber(0, 'number')).toBe(0)
expect(convertStringToNumber('', 'number')).toBe('')
expect(convertStringToNumber('010', 'string')).toBe('010')
expect(convertStringToNumber('a010', 'number')).toBe(undefined)
})
})
Example #28
Source File: workspace-service.spec.ts From leapp with Mozilla Public License 2.0 | 6 votes |
describe("WorkspaceService", () => {
test("getWorkspace - return an instance of the workspace model", () => {
const repository = {
getWorkspace: jest.fn(() => new Workspace()),
};
const workspaceService = new WorkspaceService(repository as any);
expect(workspaceService.getWorkspace()).toBeInstanceOf(Workspace);
expect(repository.getWorkspace).toHaveBeenCalled();
});
test("persistsWorkspace - persist the changes in the workspace", () => {
let modifiedWorkspace;
const repository = {
getWorkspace: jest.fn(() => new Workspace()),
persistWorkspace: jest.fn((workspace: Workspace) => {
modifiedWorkspace = Object.assign(workspace, {});
}),
};
const workspaceService = new WorkspaceService(repository as any);
const newWorkspace = workspaceService.getWorkspace();
newWorkspace.colorTheme = "testValue";
workspaceService.persistWorkspace(newWorkspace);
expect(newWorkspace).toStrictEqual(modifiedWorkspace);
expect(repository.persistWorkspace).toHaveBeenCalled();
});
test("workspaceExists - verify if the workspace exists or not", () => {
const repository = {
getWorkspace: jest.fn(() => new Workspace()),
};
const workspaceService = new WorkspaceService(repository as any);
expect(workspaceService.workspaceExists()).toStrictEqual(true);
expect(repository.getWorkspace).toHaveBeenCalled();
});
});
Example #29
Source File: githubstatus.test.ts From ghaction-github-status with MIT License | 6 votes |
describe('githubstatus', () => {
it('returns GitHub Status (status)', async () => {
const status = await githubstatus.status();
expect(status?.indicator).not.toEqual('');
});
it('returns GitHub Status (summary)', async () => {
const summary = await githubstatus.summary();
expect(summary?.status.indicator).not.toEqual('');
expect(summary?.components?.length).toBeGreaterThan(0);
});
});