Skip to content

refactor: use jasmine expectAsync instead of try/catch in tests #18535

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
"@types/glob": "^5.0.33",
"@types/gulp": "3.8.32",
"@types/inquirer": "^0.0.43",
"@types/jasmine": "^3.4.0",
"@types/jasmine": "^3.5.4",
"@types/marked": "^0.4.2",
"@types/merge2": "^0.3.30",
"@types/minimist": "^1.2.0",
Expand Down Expand Up @@ -113,12 +113,12 @@
"highlight.js": "^9.11.0",
"husky": "^1.3.1",
"inquirer": "^6.2.0",
"jasmine-core": "^3.3.0",
"jasmine-core": "^3.5.0",
"karma": "^4.4.1",
"karma-browserstack-launcher": "^1.3.0",
"karma-chrome-launcher": "^2.2.0",
"karma-firefox-launcher": "^1.0.1",
"karma-jasmine": "^2.0.1",
"karma-jasmine": "^3.1.1",
"karma-parallel": "^0.3.0",
"karma-requirejs": "^1.1.0",
"karma-sauce-launcher": "^2.0.2",
Expand Down Expand Up @@ -156,6 +156,8 @@
},
"resolutions": {
"dgeni-packages/typescript": "3.7.4",
"@bazel/jasmine/jasmine": "3.5.0",
"@bazel/jasmine/jasmine-core": "3.5.0",
Copy link
Member Author

Choose a reason for hiding this comment

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

These are temporarily until @bazel/jasmine has been updated to jasmine v3.5.0. I created a ticket for tracking: DEV-37, and also sent a PR upstream to update jasmine.

"**/graceful-fs": "4.2.2"
}
}
10 changes: 8 additions & 2 deletions src/cdk/a11y/key-manager/list-key-manager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {ActiveDescendantKeyManager} from './activedescendant-key-manager';
import {FocusKeyManager} from './focus-key-manager';
import {ListKeyManager, ListKeyManagerModifierKey, ListKeyManagerOption} from './list-key-manager';


class FakeFocusable {
/** Whether the item is disabled or not. */
disabled = false;
Expand Down Expand Up @@ -68,7 +67,14 @@ describe('Key managers', () => {
});

describe('ListKeyManager', () => {
let keyManager: ListKeyManager<FakeFocusable>;
// We have a spy on the `setActiveItem` method of the list key manager. That method has
// multiple overloads and TypeScript is unable to infer the right parameters when calls are
// checked using jasmine's `hasBeenCalledWith` matcher. We work around this by explicitly
// specifying the overload signature that should be used.
// TODO: remove if https://github.com/DefinitelyTyped/DefinitelyTyped/issues/42455 is solved.
let keyManager: Omit<ListKeyManager<FakeFocusable>, 'setActiveItem'> & {
setActiveItem(index: number): void;
};

beforeEach(() => {
itemList.items = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,9 @@ describe('global stylesheets migration', () => {
writeFile('/sub_project/node_modules/materialize.css/package.json', '');
writeFile('/sub_project/assets/test.css', subProjectStylesheet);

let error: any = null;
try {
await runFixers()
} catch (e) {
error = e;
}

expect(error).toBeNull();
// Run the fixers and expect no error to be thrown.
await expectAsync(runFixers()).not.toBeRejected();

// if the external stylesheet that is not of a project target would have been checked
// by accident, the stylesheet would differ from the original file content.
expect(appTree.readContent('/sub_project/assets/test.css')).toBe(subProjectStylesheet);
Expand Down
26 changes: 0 additions & 26 deletions src/cdk/testing/private/expect-async-error.ts

This file was deleted.

1 change: 0 additions & 1 deletion src/cdk/testing/private/public-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/

export * from './expect-async-error';
export * from './wrapped-error-message';
export * from './mock-ng-zone';
export * from './text-dedent';
Expand Down
16 changes: 10 additions & 6 deletions src/cdk/testing/tests/protractor.e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
HarnessLoader,
TestElement
} from '@angular/cdk/testing';
import {expectAsyncError} from '@angular/cdk/testing/private';
import {ProtractorHarnessEnvironment} from '@angular/cdk/testing/protractor';
import {browser} from 'protractor';
import {MainComponentHarness} from './harnesses/main-component-harness';
Expand Down Expand Up @@ -392,11 +391,16 @@ describe('ProtractorHarnessEnvironment', () => {
});

it('should throw when multiple queries fail to match', async () => {
await expectAsyncError(() => harness.missingElementsAndHarnesses(),
'Error: Failed to find element matching one of the following queries:' +
'\n(TestElement for element matching selector: ".not-found"),' +
'\n(SubComponentHarness with host element matching selector: "test-sub" satisfying' +
' the constraints: title = /not found/)');
try {
await harness.missingElementsAndHarnesses();
fail('Expected to throw.');
} catch (e) {
expect(e.message).toBe(
'Failed to find element matching one of the following queries:' +
'\n(TestElement for element matching selector: ".not-found"),' +
'\n(SubComponentHarness with host element matching selector: "test-sub" satisfying' +
' the constraints: title = /not found/)');
}
});

it('should check if element is focused', async () => {
Expand Down
10 changes: 7 additions & 3 deletions src/cdk/testing/tests/testbed.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
HarnessLoader,
TestElement
} from '@angular/cdk/testing';
import {expectAsyncError} from '@angular/cdk/testing/private';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {async, ComponentFixture, fakeAsync, TestBed} from '@angular/core/testing';
import {FakeOverlayHarness} from './harnesses/fake-overlay-harness';
Expand Down Expand Up @@ -435,11 +434,16 @@ describe('TestbedHarnessEnvironment', () => {
});

it('should throw when multiple queries fail to match', async () => {
await expectAsyncError(() => harness.missingElementsAndHarnesses(),
'Error: Failed to find element matching one of the following queries:' +
try {
await harness.missingElementsAndHarnesses();
fail('Expected to throw.');
} catch (e) {
expect(e.message).toBe(
'Failed to find element matching one of the following queries:' +
'\n(TestElement for element matching selector: ".not-found"),' +
'\n(SubComponentHarness with host element matching selector: "test-sub" satisfying' +
' the constraints: title = /not found/)');
}
});

it('should check if element is focused', async () => {
Expand Down
5 changes: 2 additions & 3 deletions src/material/autocomplete/testing/shared.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {OverlayContainer} from '@angular/cdk/overlay';
import {expectAsyncError} from '@angular/cdk/testing/private';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
Expand Down Expand Up @@ -131,8 +130,8 @@ export function runHarnessTests(
it('should throw when selecting an option that is not available', async () => {
const input = await loader.getHarness(autocompleteHarness.with({selector: '#plain'}));
await input.enterText('New');
await expectAsyncError(() => input.selectOption({text: 'Texas'}),
/Error: Could not find a mat-option matching {"text":"Texas"}/);
await expectAsync(input.selectOption({text: 'Texas'})).toBeRejectedWithError(
/Could not find a mat-option matching {"text":"Texas"}/);
});
}

Expand Down
5 changes: 2 additions & 3 deletions src/material/grid-list/testing/shared.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {HarnessLoader} from '@angular/cdk/testing';
import {expectAsyncError} from '@angular/cdk/testing/private';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
Expand Down Expand Up @@ -91,8 +90,8 @@ export function runHarnessTests(
]);
expect(await tiles[0].getHeaderText()).toBe('Three');
expect(await tiles[1].getHeaderText()).toBe('Three');
await expectAsyncError(
() => gridList.getTileAtPosition({row: 2, column: 0}), /Could not find tile/);
await expectAsync(gridList.getTileAtPosition({row: 2, column: 0}))
.toBeRejectedWithError(/Could not find tile/);

// Update the fourth tile to span over two rows. The previous position
// should now be valid and the fourth tile should be returned.
Expand Down
9 changes: 4 additions & 5 deletions src/material/menu/testing/shared.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {OverlayContainer} from '@angular/cdk/overlay';
import {expectAsyncError} from '@angular/cdk/testing/private';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
Expand Down Expand Up @@ -155,8 +154,8 @@ export function runHarnessTests(

it('should throw when item is not found', async () => {
const menu1 = await loader.getHarness(MatMenuHarness.with({triggerText: 'Menu 1'}));
await expectAsyncError(() => menu1.clickItem({text: 'Fake Item'}),
/Error: Could not find item matching {"text":"Fake Item"}/);
await expectAsync(menu1.clickItem({text: 'Fake Item'})).toBeRejectedWithError(
/Could not find item matching {"text":"Fake Item"}/);
});

it('should select item in nested menu', async () => {
Expand All @@ -167,8 +166,8 @@ export function runHarnessTests(

it('should throw when intermediate item does not have submenu', async () => {
const menu1 = await loader.getHarness(MatMenuHarness.with({triggerText: 'Menu 1'}));
await expectAsyncError(() => menu1.clickItem({text: 'Leaf Item 1'}, {}),
/Error: Item matching {"text":"Leaf Item 1"} does not have a submenu/);
await expectAsync(menu1.clickItem({text: 'Leaf Item 1'}, {})).toBeRejectedWithError(
/Item matching {"text":"Leaf Item 1"} does not have a submenu/);
});
});
}
Expand Down
13 changes: 6 additions & 7 deletions src/material/paginator/testing/shared.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatPaginatorModule, PageEvent, MatPaginator} from '@angular/material/paginator';
import {MatPaginatorHarness} from './paginator-harness';
import {expectAsyncError} from '@angular/cdk/testing/private';

/** Shared tests to run on both the original and MDC-based paginator. */
export function runHarnessTests(
Expand Down Expand Up @@ -91,8 +90,8 @@ export function runHarnessTests(
instance.showFirstLastButtons = false;
fixture.detectChanges();

await expectAsyncError(() => paginator.goToFirstPage(),
/Error: Could not find first page button inside paginator/);
await expectAsync(paginator.goToFirstPage()).toBeRejectedWithError(
/Could not find first page button inside paginator/);
});

it('should throw an error if the last page button is not available', async () => {
Expand All @@ -101,8 +100,8 @@ export function runHarnessTests(
instance.showFirstLastButtons = false;
fixture.detectChanges();

await expectAsyncError(() => paginator.goToLastPage(),
/Error: Could not find last page button inside paginator/);
await expectAsync(paginator.goToLastPage()).toBeRejectedWithError(
/Could not find last page button inside paginator/);
});

it('should throw an error if the page size selector is not available', async () => {
Expand All @@ -111,8 +110,8 @@ export function runHarnessTests(
instance.pageSizeOptions = [];
fixture.detectChanges();

await expectAsyncError(() => paginator.setPageSize(10),
/Error: Cannot find page size selector in paginator/);
await expectAsync(paginator.setPageSize(10)).toBeRejectedWithError(
/Cannot find page size selector in paginator/);
});
}

Expand Down
28 changes: 8 additions & 20 deletions src/material/radio/testing/shared.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {Platform} from '@angular/cdk/platform';
import {expectAsyncError} from '@angular/cdk/testing/private';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
Expand Down Expand Up @@ -57,15 +56,10 @@ export function runHarnessTests(radioModule: typeof MatRadioModule,
fixture.componentInstance.thirdGroupButtonName = 'other-name';
fixture.detectChanges();

let errorMessage: string | null = null;
try {
await loader.getAllHarnesses(radioGroupHarness.with({name: 'third-group-name'}));
} catch (e) {
errorMessage = e.toString();
}

expect(errorMessage).toMatch(
/locator found a radio-group with name "third-group-name".*have mismatching names/);
await expectAsync(
loader.getAllHarnesses(radioGroupHarness.with({name: 'third-group-name'})))
.toBeRejectedWithError(
/locator found a radio-group with name "third-group-name".*have mismatching names/);
});

it('should get name of radio-group', async () => {
Expand All @@ -83,14 +77,8 @@ export function runHarnessTests(radioModule: typeof MatRadioModule,
fixture.componentInstance.thirdGroupButtonName = 'other-button-name';
fixture.detectChanges();

let errorMessage: string | null = null;
try {
await groups[2].getName();
} catch (e) {
errorMessage = e.toString();
}

expect(errorMessage).toMatch(/Radio buttons in radio-group have mismatching names./);
await expectAsync(groups[2].getName())
.toBeRejectedWithError(/Radio buttons in radio-group have mismatching names./);
});

it('should get id of radio-group', async () => {
Expand Down Expand Up @@ -149,8 +137,8 @@ export function runHarnessTests(radioModule: typeof MatRadioModule,

it('should throw error when checking invalid radio button', async () => {
const group = await loader.getHarness(radioGroupHarness.with({name: 'my-group-1-name'}));
await expectAsyncError(() => group.checkRadioButton({label: 'opt4'}),
/Error: Could not find radio button matching {"label":"opt4"}/);
await expectAsync(group.checkRadioButton({label: 'opt4'})).toBeRejectedWithError(
/Could not find radio button matching {"label":"opt4"}/);
});
});

Expand Down
11 changes: 2 additions & 9 deletions src/material/schematics/ng-add/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,15 +244,8 @@ describe('ng-add schematic', () => {
it('should throw an error if the "build" target has been changed', async () => {
overwriteTargetBuilder(appTree, 'build', 'thirdparty-builder');

let message: string|null = null;

try {
await runner.runSchematicAsync('ng-add-setup-project', {}, appTree).toPromise();
} catch (e) {
message = e.message;
}

expect(message).toMatch(/not using the default builders.*build/);
await expectAsync(runner.runSchematicAsync('ng-add-setup-project', {}, appTree).toPromise())
.toBeRejectedWithError(/not using the default builders.*build/);
});

it('should warn if the "test" target has been changed', async () => {
Expand Down
11 changes: 3 additions & 8 deletions src/material/schematics/ng-generate/address-form/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,10 @@ describe('Material address-form schematic', () => {

it('should throw if no name has been specified', async () => {
const appTree = await createTestApp(runner);
let message: string|null = null;

try {
await runner.runSchematicAsync('address-form', {project: 'material'}, appTree).toPromise();
} catch (e) {
message = e.message;
}

expect(message).toMatch(/required property 'name'/);
await expectAsync(
runner.runSchematicAsync('address-form', {project: 'material'}, appTree).toPromise())
.toBeRejectedWithError(/required property 'name'/);
});

describe('style option', () => {
Expand Down
11 changes: 3 additions & 8 deletions src/material/schematics/ng-generate/dashboard/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,10 @@ describe('material-dashboard-schematic', () => {

it('should throw if no name has been specified', async () => {
const appTree = await createTestApp(runner);
let message: string|null = null;

try {
await runner.runSchematicAsync('dashboard', {project: 'material'}, appTree).toPromise();
} catch (e) {
message = e.message;
}

expect(message).toMatch(/required property 'name'/);
await expectAsync(
runner.runSchematicAsync('dashboard', {project: 'material'}, appTree).toPromise())
.toBeRejectedWithError(/required property 'name'/);
});

describe('style option', () => {
Expand Down
11 changes: 3 additions & 8 deletions src/material/schematics/ng-generate/navigation/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,10 @@ describe('material-navigation-schematic', () => {

it('should throw if no name has been specified', async () => {
const appTree = await createTestApp(runner);
let message: string|null = null;

try {
await runner.runSchematicAsync('navigation', {project: 'material'}, appTree).toPromise();
} catch (e) {
message = e.message;
}

expect(message).toMatch(/required property 'name'/);
await expectAsync(
runner.runSchematicAsync('navigation', {project: 'material'}, appTree).toPromise())
.toBeRejectedWithError(/required property 'name'/);
});

describe('style option', () => {
Expand Down
Loading