angular/components · error · Error

Cannot read " " because it does not exist.

Error message

Cannot read "${filePath}" because it does not exist.

What it means

getFileContent is a schematic-testing helper that reads a file from a schematic Tree. Tree.read returns undefined/falsy when the path doesn't exist in the virtual file system, and the helper surfaces that as this explicit error naming the path.

Solutions

  1. Verify the path exists in the tree before reading: if (!tree.exists(filePath)) handle or fail with a clear message.
  2. Fix the file path (check the schematic's output paths; use tree.files to list what exists).
  3. Ensure the schematic under test actually creates the file (run/apply the rule before asserting).
  4. In tests, use tree.readDir or log tree.files to debug which files were generated.

Example fix

// before
const content = getFileContent(tree, '/src/app/old.module.ts');
// after
const path = '/src/app/app.module.ts';
if (!tree.exists(path)) {
  throw new Error(`Expected ${path}; tree has: ${tree.files.join(', ')}`);
}
const content = getFileContent(tree, path);
Defensive patterns

Strategy: validation

Validate before calling

if (!tree.exists(filePath)) {
  throw new Error(`Expected file missing from schematic tree: ${filePath}`);
}
const content = getFileContent(tree, filePath);

Try / catch

try {
  const content = getFileContent(tree, path);
} catch (e) {
  if ((e as Error).message.startsWith('Cannot read')) {
    console.error(`Tree files: ${tree.files.join(', ')}`);
  }
  throw e;
}

Prevention

When it happens

Trigger: Calling getFileContent(tree, 'src/app/app.module.ts') (or helpers packageJson/module/component/test that use it) during a schematic test when the file was never created by the rule under test, or the path string is wrong/relative-to-wrong-root.

Common situations: Schematic renamed or moved a file so the expected path doesn't exist; testing a rule that only writes some files; path typo or missing leading directory; asserting against files outside the tree root.

Related errors


AI-assisted analysis of angular/components@0411926e7d (2026-08-31). Data as JSON: /api/errors/d3549133ff467fae. Report an issue: GitHub.

Appendix: source

Thrown at src/cdk/schematics/testing/file-content.ts:16

/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.dev/license
 */

import {Tree} from '@angular-devkit/schematics';

/** Gets the content of a specified file from a schematic tree. */
export function getFileContent(tree: Tree, filePath: string): string {
  const contentBuffer = tree.read(filePath);

  if (!contentBuffer) {
    throw new Error(`Cannot read "${filePath}" because it does not exist.`);
  }

  return contentBuffer.toString();
}

View on GitHub (pinned to 0411926e7d)