Skip to content

Commit

Permalink
test(@angular-devkit/build-angular): add support for builder harness …
Browse files Browse the repository at this point in the history
…directory expectations

When using the builder harness in unit tests, expectations can now be made directly for
directories. Currently the existence, or lack thereof, can be tested using the harness.
This is similar to be existing file expectations. More capability may be added as needed
in the future.

(cherry picked from commit f18076a)
  • Loading branch information
clydin authored and alan-agius4 committed Dec 11, 2023
1 parent f63566e commit fcd9adc
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
import { WorkspaceHost } from '@angular-devkit/architect/node';
import { TestProjectHost } from '@angular-devkit/architect/testing';
import { getSystemPath, json, logging } from '@angular-devkit/core';
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import fs from 'node:fs/promises';
import { dirname, join } from 'node:path';
import {
Expand Down Expand Up @@ -351,6 +351,12 @@ export class BuilderHarness<T> {
return existsSync(fullPath);
}

hasDirectory(path: string): boolean {
const fullPath = this.resolvePath(path);

return statSync(fullPath, { throwIfNoEntry: false })?.isDirectory() ?? false;
}

hasFileMatch(directory: string, pattern: RegExp): boolean {
const fullPath = this.resolvePath(directory);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ export class JasmineBuilderHarness<T> extends BuilderHarness<T> {
expectFile(path: string): HarnessFileMatchers {
return expectFile(path, this);
}
expectDirectory(path: string): HarnessDirectoryMatchers {
return expectDirectory(path, this);
}
}

export interface HarnessFileMatchers {
Expand All @@ -51,6 +54,11 @@ export interface HarnessFileMatchers {
readonly size: jasmine.Matchers<number>;
}

export interface HarnessDirectoryMatchers {
toExist(): boolean;
toNotExist(): boolean;
}

/**
* Add a Jasmine expectation filter to an expectation that always fails with a message.
* @param base The base expectation (`expect(...)`) to use.
Expand Down Expand Up @@ -125,3 +133,23 @@ export function expectFile<T>(path: string, harness: BuilderHarness<T>): Harness
},
};
}

export function expectDirectory<T>(
path: string,
harness: BuilderHarness<T>,
): HarnessDirectoryMatchers {
return {
toExist() {
const exists = harness.hasDirectory(path);
expect(exists).toBe(true, 'Expected directory to exist: ' + path);

return exists;
},
toNotExist() {
const exists = harness.hasDirectory(path);
expect(exists).toBe(false, 'Expected directory to not exist: ' + path);

return !exists;
},
};
}

0 comments on commit fcd9adc

Please sign in to comment.