Skip to content

Commit

Permalink
fix rest of tests
Browse files Browse the repository at this point in the history
  • Loading branch information
M-Kusumgar committed Nov 16, 2024
1 parent 748c80f commit dfc53df
Show file tree
Hide file tree
Showing 13 changed files with 124 additions and 143 deletions.
14 changes: 7 additions & 7 deletions app/server/tests/apiService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { api } from "../src/apiService";
describe("apiService", () => {
beforeEach(() => {
mockAxios.reset();
jest.resetAllMocks();
vi.resetAllMocks();
});

const mockReq = {
Expand All @@ -23,17 +23,17 @@ describe("apiService", () => {
} as any;

const mockRes = {
status: jest.fn(),
header: jest.fn(),
end: jest.fn()
status: vi.fn(),
header: vi.fn(),
end: vi.fn()
} as any;

const postData = "posted data";

const responseData = { data: "test get" };
const responseHeaders = { respHeader1: "rh1", respHeader2: "rh2" };

const mockNext = jest.fn();
const mockNext = vi.fn();

const testExpectedResponse = () => {
expect(mockRes.status.mock.calls[0][0]).toBe(200);
Expand All @@ -50,13 +50,13 @@ describe("apiService", () => {
headers: AxiosRequestHeaders,
transformResponse: AxiosResponseTransformer
) => {
expect(headers).toStrictEqual({
expect(headers.toJSON()).toEqual({
Accept: "application/json",
"Content-Type": "text",
ArrayHeader: "arr1,arr2"
});
const transformTest = "{\"json\": \"test\"}";
expect((transformResponse as AxiosResponseTransformer)(transformTest)).toBe(transformTest);
expect((transformResponse as any)(transformTest)).toBe(transformTest);
};

const testExpectedError = () => {
Expand Down
12 changes: 6 additions & 6 deletions app/server/tests/appFileReader.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import * as fs from "fs";
import fs from "fs";
import { AppFileReader } from "../src/appFileReader";

describe("DefaultCodeReader", () => {
afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

it("returns lines from file when file exists", () => {
const mockExistsSync = jest.spyOn(fs, "existsSync").mockReturnValue(true);
const mockReadFileSync = jest.spyOn(fs, "readFileSync").mockReturnValue("line1\nline2\nline3");
const mockExistsSync = vi.spyOn(fs, "existsSync").mockReturnValue(true);
const mockReadFileSync = vi.spyOn(fs, "readFileSync").mockReturnValue("line1\nline2\nline3");

const result = new AppFileReader("/testDir", "R").readFile("TestApp");
expect(result).toStrictEqual(["line1", "line2", "line3"]);
Expand All @@ -18,8 +18,8 @@ describe("DefaultCodeReader", () => {
});

it("returns empty string array when file does not exist", () => {
const mockExistsSync = jest.spyOn(fs, "existsSync").mockReturnValue(false);
const mockReadFileSync = jest.spyOn(fs, "readFileSync");
const mockExistsSync = vi.spyOn(fs, "existsSync").mockReturnValue(false);
const mockReadFileSync = vi.spyOn(fs, "readFileSync");

const result = new AppFileReader("/testDir", "R").readFile("TestApp");
expect(result).toStrictEqual([]);
Expand Down
10 changes: 5 additions & 5 deletions app/server/tests/configReader.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import * as fs from "fs";
import fs from "fs";
import { ConfigReader } from "../src/configReader";

describe("configReader", () => {
beforeEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});

it("returns null when config not found", () => {
const mockExistsSync = jest.spyOn(fs, "existsSync").mockReturnValue(false);
const mockExistsSync = vi.spyOn(fs, "existsSync").mockReturnValue(false);

const result = new ConfigReader("root").readConfigFile("test.config");

Expand All @@ -17,8 +17,8 @@ describe("configReader", () => {
});

it("returns parsed config file contents", () => {
const mockExistsSync = jest.spyOn(fs, "existsSync").mockReturnValue(true);
const mockReadFileSync = jest.spyOn(fs, "readFileSync").mockReturnValue("{\"test\": \"value\"}");
const mockExistsSync = vi.spyOn(fs, "existsSync").mockReturnValue(true);
const mockReadFileSync = vi.spyOn(fs, "readFileSync").mockReturnValue("{\"test\": \"value\"}");

const result = new ConfigReader("root").readConfigFile("test.config");

Expand Down
19 changes: 9 additions & 10 deletions app/server/tests/handleError.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable import/first */
// mock json response before import errors
const mockJsonResponseError = jest.fn();
jest.mock("../src/jsonResponse", () => { return { jsonResponseError: mockJsonResponseError }; });
const { mockJsonResponseError } = vi.hoisted(() => ({ mockJsonResponseError: vi.fn() }));
vi.mock("../src/jsonResponse", () => { return { jsonResponseError: mockJsonResponseError }; });

import { handleError } from "../src/errors/handleError";
import { WodinError } from "../src/errors/wodinError";
Expand All @@ -17,18 +16,18 @@ const mockRequest = (accept = "application/json,*/*") => {
};

const mockStatus = {
render: jest.fn()
render: vi.fn()
};

const mockResponse = () => {
return {
status: jest.fn().mockReturnValue(mockStatus)
status: vi.fn().mockReturnValue(mockStatus)
} as any;
};

describe("handeError", () => {
afterEach(() => {
jest.resetAllMocks();
vi.resetAllMocks();
});

const testUnexpectedErrorMsg = (msg: string) => {
Expand All @@ -42,7 +41,7 @@ describe("handeError", () => {
const err = new WodinError("test wodin error", 404, ErrorType.NOT_FOUND);
const req = mockRequest();
const res = mockResponse();
handleError(err, req, res, jest.fn());
handleError(err, req, res, vi.fn());

// check expected data has been attached to request
expect(req.errorType).toBe(ErrorType.NOT_FOUND);
Expand All @@ -61,7 +60,7 @@ describe("handeError", () => {
const err = new Error("something bad");
const req = mockRequest();
const res = mockResponse();
handleError(err, req, res, jest.fn());
handleError(err, req, res, vi.fn());

// check expected data has been attached to request
expect(req.errorType).toBe(ErrorType.OTHER_ERROR);
Expand All @@ -81,7 +80,7 @@ describe("handeError", () => {
const err = new WodinWebError("test wodin web error", 404, ErrorType.NOT_FOUND, "test-view", options);
const req = mockRequest("text/html");
const res = mockResponse();
handleError(err, req, res, jest.fn());
handleError(err, req, res, vi.fn());

// check expected data has been attached to request
expect(req.errorType).toBe(ErrorType.NOT_FOUND);
Expand All @@ -98,7 +97,7 @@ describe("handeError", () => {
const err = new Error("something bad");
const req = mockRequest("text/html");
const res = mockResponse();
handleError(err, req, res, jest.fn());
handleError(err, req, res, vi.fn());

// check expected data has been attached to request
expect(req.errorType).toBe(ErrorType.OTHER_ERROR);
Expand Down
2 changes: 1 addition & 1 deletion app/server/tests/integration/integrationTest.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
const request = require("supertest");
import request from "supertest";

export const wodin = request("http://localhost:3000");
8 changes: 4 additions & 4 deletions app/server/tests/jsonResponse.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { jsonResponseError, jsonResponseSuccess } from "../src/jsonResponse";

describe("jsonResponse", () => {
const mockHeader = jest.fn();
const mockStatus = jest.fn();
const mockEnd = jest.fn();
const mockHeader = vi.fn();
const mockStatus = vi.fn();
const mockEnd = vi.fn();
const mockRes = {
header: mockHeader,
status: mockStatus,
end: mockEnd
};

beforeEach(() => {
jest.resetAllMocks();
vi.resetAllMocks();
});

it("jsonResponseSuccess adds header and expected response text", () => {
Expand Down
18 changes: 11 additions & 7 deletions app/server/tests/logging.test.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
// mock morgan before import logging
const mockMorganResult = {};
const mockMorgan = jest.fn().mockReturnValue(mockMorganResult);
const mockMorganToken = jest.fn();
const { mockMorgan, mockMorganToken, mockMorganResult } = vi.hoisted(() => {
const mockMorganResult = {};
return {
mockMorganResult,
mockMorgan: vi.fn().mockReturnValue({}),
mockMorganToken: vi.fn()
}
});
(mockMorgan as any).token = mockMorganToken;
jest.mock("morgan", () => mockMorgan);
vi.mock("morgan", () => ({default: mockMorgan}));

// eslint-disable-next-line import/first
import { initialiseLogging } from "../src/logging";

describe("logging", () => {
it("initialiseLogging registers custom tokens and format", () => {
const mockApplication = { use: jest.fn() } as any;
const mockApplication = { use: vi.fn() } as any;
initialiseLogging(mockApplication);

// Test custom tokens have been registered
Expand All @@ -32,7 +36,7 @@ describe("logging", () => {
expect(errorStackFn(testRequest)).toBe("TEST ERROR STACK");

// Test expected custom format has been registered
expect(mockApplication.use.mock.calls[0][0]).toBe(mockMorganResult);
expect(mockApplication.use.mock.calls[0][0]).toStrictEqual(mockMorganResult);
const customFormatFn = mockMorgan.mock.calls[0][0];

const testReq = {
Expand Down
36 changes: 16 additions & 20 deletions app/server/tests/redis.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { redisConnection } from "../src/redis";

describe("redis", () => {
const mockConsoleLog = jest.fn();
const mockConsoleLog = vi.fn();
const realConsoleLog = console.log;
const realArgs = process.argv;

Expand All @@ -15,30 +15,26 @@ describe("redis", () => {
});

afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

it("can connect", (done) => {
const errorCallback = jest.fn();
it("can connect", async () => {
const errorCallback = vi.fn();
const redis = redisConnection("redis://localhost:6379", errorCallback);
setTimeout(() => {
redis.disconnect();
expect(mockConsoleLog).toBeCalledTimes(1);
expect(mockConsoleLog.mock.calls[0][0])
.toBe("Connected to Redis server redis://localhost:6379");
expect(errorCallback).not.toHaveBeenCalled();
done();
}, 200);
await new Promise(res => setTimeout(res, 200));
redis.disconnect();
expect(mockConsoleLog).toBeCalledTimes(1);
expect(mockConsoleLog.mock.calls[0][0])
.toBe("Connected to Redis server redis://localhost:6379");
expect(errorCallback).not.toHaveBeenCalled();
});

it("calls error callback if cannot connect", (done) => {
const errorCallback = jest.fn();
it("calls error callback if cannot connect", async () => {
const errorCallback = vi.fn();
redisConnection("redis://localhost:1234", errorCallback);
setTimeout(() => {
expect(mockConsoleLog.mock.calls[0][0].message)
.toContain("connect ECONNREFUSED 127.0.0.1:1234");
expect(errorCallback).toHaveBeenCalled();
done();
}, 200);
await new Promise(res => setTimeout(res, 200));
expect(mockConsoleLog.mock.calls[0][0].message)
.toContain("connect ECONNREFUSED 127.0.0.1:1234");
expect(errorCallback).toHaveBeenCalled();
});
});
31 changes: 15 additions & 16 deletions app/server/tests/routes/apps.test.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
import { AppsController } from "../../src/controllers/appsController";
import { SessionsController } from "../../src/controllers/sessionsController";
import bodyParser from "body-parser";

describe("odin routes", () => {
const express = require("express");
const bodyParser = require("body-parser");
const { mockRouter } = vi.hoisted(() => ({
mockRouter: {
get: vi.fn(),
post: vi.fn()
}
}));

const mockRouter = {
get: jest.fn(),
post: jest.fn()
};
const realRouter = express.Router;
vi.mock("express", () => ({
Router: () => mockRouter
}));

const spyText = jest.spyOn(bodyParser, "text");

beforeAll(() => {
express.Router = () => mockRouter;
describe("odin routes", async () => {
beforeEach(() => {
vi.resetAllMocks()
});

afterAll(() => {
express.Router = realRouter;
});
const spyText = vi.spyOn(bodyParser, "text");

it.only("registers expected routes", async () => {
it("registers expected routes", async () => {
await import("../../src/routes/apps");

expect(mockRouter.get).toBeCalledTimes(3);
Expand Down
24 changes: 12 additions & 12 deletions app/server/tests/routes/config.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { ConfigController } from "../../src/controllers/configController";

describe("config routes", () => {
const express = require("express");

const mockRouter = {
get: jest.fn()
};
const realRouter = express.Router;
const { mockRouter } = vi.hoisted(() => ({
mockRouter: {
get: vi.fn(),
post: vi.fn()
}
}));

beforeAll(() => {
express.Router = () => mockRouter;
});
vi.mock("express", () => ({
Router: () => mockRouter
}));

afterAll(() => {
express.Router = realRouter;
describe("config routes", () => {
beforeEach(() => {
vi.resetAllMocks()
});

it("registers expected routes", async () => {
Expand Down
Loading

0 comments on commit dfc53df

Please sign in to comment.