Skip to content

Commit

Permalink
feat(Cypress-SignalR-Mock): Added support for using Cypress-SignalR-M…
Browse files Browse the repository at this point in the history
…ock with Vitest unit testing in the same way as using it for Cypress
  • Loading branch information
JasonLandbridge committed Jul 16, 2023
1 parent 1c94081 commit 91ac04e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
36 changes: 27 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,38 @@ import HubConnectionMock from "./types/HubConnectionMock";
import { setupCypressCommands } from "./cypress-commands";
import IMockData from "./types/IMockData";
import IServerInvoke from "./types/IServerInvoke";
import { getCypressSignalrMockData, isCypressRunning } from "./utils.ts";
import {
getCypressSignalrMockData,
isCypressRunning,
isInVitestMode,
} from "./utils.ts";
import Log from "./log.ts";

setupCypressCommands();
useCypressSignalRMock("default");

export function useCypressSignalRMock(
name: string,
{ debug }: Partial<{ debug?: boolean }> = {}
{
debug,
enableForVitest,
}: Partial<{ debug?: boolean; enableForVitest?: boolean }> = {}
): HubConnection | null {
if (!isCypressRunning()) {
return null;
}

if (debug) {
Log.setLogLevel(4);
}
if (!enableForVitest && isInVitestMode()) {
Log.info(
`Vitest is running but 'enableForVitest' is ${enableForVitest}, skip enabling CypressSignalRMock...`
);
}

const mock = new HubConnectionMock(name);
getCypressSignalrMockData().mocks.push(mock);
return <HubConnection>(mock as unknown);
if (isCypressRunning() || (enableForVitest && isInVitestMode())) {
const mock = new HubConnectionMock(name);
getCypressSignalrMockData().mocks.push(mock);
return <HubConnection>(mock as unknown);
}
return null;
}

/**
Expand Down Expand Up @@ -77,3 +88,10 @@ declare global {
}
}
}

export {
hubPublish,
hubVerify,
hubClear,
hubPrintData,
} from "./cypress-commands";
8 changes: 8 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,11 @@ export function isSSR(): boolean {
}
return false;
}

export function isInVitestMode(): boolean {
return (
typeof process !== "undefined" &&
process?.env?.hasOwnProperty("VITEST") &&
process.env.VITEST === "true"
);
}

0 comments on commit 91ac04e

Please sign in to comment.