summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/packages/ng-schematics/src/builders/puppeteer/index.ts
blob: 45aec95152368f6a37815564fe78caec565960d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import {spawn} from 'child_process';

import {
  createBuilder,
  BuilderContext,
  BuilderOutput,
  targetFromTargetString,
  BuilderRun,
} from '@angular-devkit/architect';
import {JsonObject} from '@angular-devkit/core';

import {PuppeteerBuilderOptions} from './types.js';

const terminalStyles = {
  blue: '\u001b[34m',
  green: '\u001b[32m',
  bold: '\u001b[1m',
  reverse: '\u001b[7m',
  clear: '\u001b[0m',
};

function getError(executable: string, args: string[]) {
  return (
    `Puppeteer E2E tests failed!` +
    '\n' +
    `Error running '${executable}' with arguments '${args.join(' ')}'.` +
    `\n` +
    'Please look at the output above to determine the issue!'
  );
}

function getExecutable(command: string[]) {
  const executable = command.shift()!;
  const error = getError(executable, command);

  if (executable === 'node') {
    return {
      executable: executable,
      args: command,
      error,
    };
  }

  return {
    executable: `./node_modules/.bin/${executable}`,
    args: command,
    error,
  };
}

async function executeCommand(context: BuilderContext, command: string[]) {
  await new Promise((resolve, reject) => {
    context.logger.debug(`Trying to execute command - ${command.join(' ')}.`);
    const {executable, args, error} = getExecutable(command);

    const child = spawn(executable, args, {
      cwd: context.workspaceRoot,
      stdio: 'inherit',
    });

    child.on('error', message => {
      console.log(message);
      reject(error);
    });

    child.on('exit', code => {
      if (code === 0) {
        resolve(true);
      } else {
        reject(error);
      }
    });
  });
}

function message(
  message: string,
  context: BuilderContext,
  type: 'info' | 'success' = 'info'
): void {
  const color = type === 'info' ? terminalStyles.blue : terminalStyles.green;
  context.logger.info(
    `${terminalStyles.bold}${terminalStyles.reverse}${color}${message}${terminalStyles.clear}`
  );
}

async function startServer(
  options: PuppeteerBuilderOptions,
  context: BuilderContext
): Promise<BuilderRun> {
  context.logger.debug('Trying to start server.');
  const target = targetFromTargetString(options.devServerTarget);
  const defaultServerOptions = await context.getTargetOptions(target);

  const overrides = {
    watch: false,
    host: defaultServerOptions['host'],
    port: defaultServerOptions['port'],
  } as JsonObject;

  message('Spawning test server...\n', context);
  const server = await context.scheduleTarget(target, overrides);
  const result = await server.result;
  if (!result.success) {
    throw new Error('Failed to spawn server! Stopping tests...');
  }

  return server;
}

async function executeE2ETest(
  options: PuppeteerBuilderOptions,
  context: BuilderContext
): Promise<BuilderOutput> {
  let server: BuilderRun | null = null;
  try {
    server = await startServer(options, context);

    message('\nRunning tests...\n', context);
    for (const command of options.commands) {
      await executeCommand(context, command);
    }

    message('\nTest ran successfully!', context, 'success');
    return {success: true};
  } catch (error) {
    if (error instanceof Error) {
      return {success: false, error: error.message};
    }
    return {success: false, error: error as any};
  } finally {
    if (server) {
      await server.stop();
    }
  }
}

export default createBuilder<PuppeteerBuilderOptions>(executeE2ETest) as any;