Skip to content

Commit

Permalink
fix: inherit mocks (resolves #183)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Apr 28, 2023
1 parent 6fb1a11 commit 6864928
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
2 changes: 1 addition & 1 deletion examples/mock.ts
Expand Up @@ -3,7 +3,7 @@ import { consola } from "./utils";
function mockFn(type) {
if (type === "info") {
return function () {
this.log("INFO INFO INFO");
this.log("(mocked fn with info tag)");
};
}
}
Expand Down
15 changes: 13 additions & 2 deletions src/consola.ts
Expand Up @@ -23,6 +23,8 @@ export class Consola {
timeout?: ReturnType<typeof setTimeout>;
};

_mockFn?: ConsolaOptions["mockFn"];

constructor(options: Partial<ConsolaOptions> = {}) {
// Options
const types = options.types || LogTypes;
Expand Down Expand Up @@ -91,10 +93,16 @@ export class Consola {
}

create(options: Partial<ConsolaOptions>): ConsolaInstance {
return new Consola({
const instance = new Consola({
...this.options,
...options,
}) as ConsolaInstance;

if (this._mockFn) {
instance.mockTypes(this._mockFn);
}

return instance;
}

withDefaults(defaults: InputLogObject): ConsolaInstance {
Expand Down Expand Up @@ -223,14 +231,17 @@ export class Consola {
}
}

mockTypes(mockFn?: (type: string, currentType: any) => any) {
mockTypes(mockFn?: ConsolaOptions["mockFn"]) {
const _mockFn = mockFn || this.options.mockFn;

this._mockFn = _mockFn;

if (typeof _mockFn !== "function") {
return;
}

for (const type in this.options.types) {
// @ts-expect-error
(this as unknown as ConsolaInstance)[type as LogType] =
_mockFn(type as LogType, this.options.types[type as LogType]) ||
(this as unknown as ConsolaInstance)[type as LogType];
Expand Down

0 comments on commit 6864928

Please sign in to comment.