Skip to content
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

feat: do not capture log messages #69

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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
78 changes: 19 additions & 59 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
import { beforeEach, afterEach, expect } from "vitest";
import { beforeEach, afterEach, expect } from 'vitest';
import * as util from 'util';
import chalk from 'chalk';
import {
ConsoleCallStacks,
ConsoleMethod,
VitestFailOnConsoleFunction,
} from './types';
import { ConsoleMethod, VitestFailOnConsoleFunction } from './types';

const LINE_RETURN = '\n';
const defaultErrorMessage = (methodName: ConsoleMethod) =>
`vitest-fail-on-console > Expected test not to call ${chalk.bold(
`console.${methodName}()`
Expand All @@ -29,7 +24,7 @@ const init = (
shouldFailOnWarn = true,
skipTest = undefined,
silenceMessage = undefined,
afterEachDelay = undefined
afterEachDelay = undefined,
}: VitestFailOnConsoleFunction = {
errorMessage: defaultErrorMessage,
shouldFailOnAssert: false,
Expand All @@ -40,60 +35,24 @@ const init = (
shouldFailOnWarn: true,
silenceMessage: undefined,
skipTest: undefined,
afterEachDelay: undefined
afterEachDelay: undefined,
}
) => {
const flushUnexpectedConsoleCalls = (
methodName: ConsoleMethod,
unexpectedConsoleCallStacks: ConsoleCallStacks
) => {
if (unexpectedConsoleCallStacks.length) {
const messages = unexpectedConsoleCallStacks.map(
([stack, message]) => {
const stackLines = stack.split(LINE_RETURN);
return (
`${chalk.red(message)}${LINE_RETURN}` +
`${stackLines
.map((line, index) => {
if (index === stackLines.length - 1) {
return chalk.white(line);
}
return chalk.gray(line);
})
.join(LINE_RETURN)}`
);
}
);

const message = errorMessage(methodName);
const doubleLineReturn = `${LINE_RETURN}${LINE_RETURN}`;
throw new Error(
`${message}${doubleLineReturn}${messages.join(
doubleLineReturn
)}`
);
}
const flushUnexpectedConsoleCalls = (methodName: ConsoleMethod) => {
throw new Error(errorMessage(methodName));
};

const patchConsoleMethod = (methodName: ConsoleMethod) => {
const unexpectedConsoleCallStacks: ConsoleCallStacks = [];
let hadConsoleCall = false;

const captureMessage = (format: unknown, ...args) => {
const handleConsoleCall = (format: unknown, ...args) => {
const message = util.format(format, ...args);
if (silenceMessage && silenceMessage(message, methodName)) {
return;
}

// Capture the call stack now, so we can warn about it later.
// The call stack has helpful information for the test author.
// Don't throw yet though b'c it might be accidentally caught and suppressed.
const { stack } = new Error();
if (stack) {
unexpectedConsoleCallStacks.push([
stack.slice(stack.indexOf(LINE_RETURN) + 1),
message,
]);
}
hadConsoleCall = true;
originalMethod(message);
};

const newAssertMethod = (
Expand All @@ -104,13 +63,13 @@ const init = (
if (assertion) {
return;
}
captureMessage(format, ...args);
handleConsoleCall(format, ...args);
};

const newMethod =
methodName === ConsoleMethod.Assert
? newAssertMethod
: captureMessage;
: handleConsoleCall;

const originalMethod = console[methodName];

Expand All @@ -126,20 +85,21 @@ const init = (
return;
}
console[methodName] = newMethod; // eslint-disable-line no-console
unexpectedConsoleCallStacks.length = 0;
hadConsoleCall = false;
});

afterEach(async () => {
if (isTestSkipped()) {
return;
}
if (afterEachDelay) {
await new Promise(resolve => setTimeout(resolve, afterEachDelay));
await new Promise((resolve) =>
setTimeout(resolve, afterEachDelay)
);
}
if (hadConsoleCall) {
flushUnexpectedConsoleCalls(methodName);
}
flushUnexpectedConsoleCalls(
methodName,
unexpectedConsoleCallStacks
);
console[methodName] = originalMethod;
});
};
Expand Down
2 changes: 0 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ export enum ConsoleMethod {
Warn = 'warn',
}

export type ConsoleCallStacks = [string, string][];

export type VitestFailOnConsoleFunction = {
shouldFailOnAssert?: boolean;
shouldFailOnDebug?: boolean;
Expand Down
2 changes: 1 addition & 1 deletion tests/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describe('vitest-fail-on-console', () => {
const configFilePath = `${fixtureDirectory}/vitest.config.ts`;
const cmd = `./node_modules/.bin/vitest related ${testFilePath} -c ${configFilePath} --run`;
return new Promise((resolve) => {
exec(cmd, (error, stdout, stderr) => {
exec(cmd, (_error, _stdout, stderr) => {
resolve({ stderr });
});
});
Expand Down