Skip to content
This repository has been archived by the owner on Mar 24, 2024. It is now read-only.

Commit

Permalink
Update the testing files
Browse files Browse the repository at this point in the history
  • Loading branch information
Marco5dev committed Oct 2, 2023
1 parent 25a4856 commit 5aa1813
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 198 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/npm-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
with:
node-version: 16
- run: npm i
- run: npm run test:jsonverse && npm run test:schema
- run: npm run test

publish-npm:
needs: build
Expand Down
2 changes: 0 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -721,8 +721,6 @@ class jsonverse {
findAll: async function () {
return this.readData(dataName);
}.bind(this),

// Implement other methods as needed
};
}
}
Expand Down
49 changes: 45 additions & 4 deletions lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,59 @@ class Schema {
const errors = {};

for (const field in this.fields) {
const fieldType = this.fields[field];
const fieldConfig = this.fields[field];
const fieldType = fieldConfig.type;
const value = data[field];

if (typeof value !== fieldType) {
if (fieldConfig.required && (value === undefined || value === null)) {
errors[field] = "This field is required.";
} else if (fieldType === "string" && typeof value !== "string") {
errors[field] = `Invalid type. Expected String, got ${typeof value}.`;
} else if (fieldType === "number" && typeof value !== "number") {
errors[field] = `Invalid type. Expected Number, got ${typeof value}.`;
} else if (
fieldType.type === "string" &&
fieldType.minlength &&
value.length < fieldType.minlength
) {
errors[
field
] = `Invalid type. Expected ${fieldType}, got ${typeof value}.`;
] = `Invalid length. Minimum length is ${fieldType.minlength}.`;
} else if (
fieldType.type === "string" &&
fieldType.maxlength &&
value.length > fieldType.maxlength
) {
errors[
field
] = `Invalid length. Maximum length is ${fieldType.maxlength}.`;
} else if (
fieldType.type === "number" &&
fieldType.min &&
value < fieldType.min
) {
errors[
field
] = `Value should be greater than or equal to ${fieldType.min}.`;
} else if (
fieldType.type === "number" &&
fieldType.max &&
value > fieldType.max
) {
errors[
field
] = `Value should be less than or equal to ${fieldType.max}.`;
} else if (
fieldType.validate &&
typeof fieldType.validate === "function" &&
!fieldType.validate(value)
) {
errors[field] = "Invalid value.";
}
}

return Object.keys(errors).length === 0 ? null : errors;
}
}

module.exports = Schema;
module.exports = Schema;
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
"description": "jsonVerse is a lightweight JSON-based database package for Node.js. It provides a simple interface to store, retrieve, and manage data using JSON files.",
"main": "index.js",
"scripts": {
"test:jsonverse": "mocha ./test/jsonverse.test.js",
"test:schema": "mocha ./test/schema.test.js"
"test": "mocha ./test/jsonverse.test.js"
},
"repository": {
"type": "git",
Expand Down
159 changes: 109 additions & 50 deletions test/jsonverse.test.js
Original file line number Diff line number Diff line change
@@ -1,57 +1,32 @@
const { expect } = require("chai");
const { jsonverse } = require("../index"); // Import the jsonverse module
const fs = require("fs").promises;
const { Schema, jsonverse } = require("../index");
const path = require("path");
const fs = require("fs");

describe("jsonverse package", () => {
let dataName = "testData"; // Change this to the actual data name you want to test
describe("Testing Schema", () => {
let Users;
let db;

// Helper function to create a new jsonverse instance for testing
function createJsonverseInstance() {
return new jsonverse({
const originalConsoleLog = console.log;
console.log = function () {};

before(async () => {
db = new jsonverse({
dataFolderPath: "./test/data", // data directory
logFolderPath: "./test/logs", // logs directory
activateLogs: true, // to enable the logs set this value to true
}); // Adjust the folder paths as needed
}
});

before(async () => {
// Check if the required folders and files exist
const dataFolderPath = "./test/data";
const logsFolderPath = "./test/logs";
const dataFilePath = path.join(dataFolderPath, `${dataName}.json`);

const [dataFolderExists, logsFolderExists, dataFileExists] =
await Promise.all([
fs
.access(dataFolderPath)
.then(() => true)
.catch(() => false),
fs
.access(logsFolderPath)
.then(() => true)
.catch(() => false),
fs
.access(dataFilePath)
.then(() => true)
.catch(() => false),
]);

// If any of the required items don't exist, create them
if (!dataFolderExists) {
await fs.mkdir(dataFolderPath, { recursive: true });
}
if (!logsFolderExists) {
await fs.mkdir(logsFolderPath, { recursive: true });
}
if (!dataFileExists) {
await fs.writeFile(dataFilePath, "[]", "utf8");
}
const userSchema = new Schema({
id: { type: "string", required: true },
name: { type: "string", required: true },
email: { type: "string", required: true },
});

Users = db.model("Users", userSchema);
});

it("should add Data", async () => {
const instance = createJsonverseInstance();

// Test the saveData function with data containing only a name
const newName = "New Test Item";
const newData = {
Expand All @@ -60,24 +35,108 @@ describe("jsonverse package", () => {
};

// Wait for the data to be saved (assuming saveData is an async function)
await instance.saveData("testData", newData);
await db.saveData("testData", newData);

instance.readData("testData").then((result) => {
db.readData("testData").then((result) => {
expect(result).to.have.property("id");
expect(result).to.have.property("name");
expect(result.name === newName);
});
});

it("should delete all items in the data file", async () => {
const instance = createJsonverseInstance();

await instance.delByDataName("testData", "1234");
await db.delByDataName("testData", "1234");

// Verify that all items were deleted
const afterDelete = instance.readData("testData");
const afterDelete = db.readData("testData");
expect(afterDelete === "[]"); // Expect an empty array
});

it("should save user data", async () => {
Users.save({
id: "johndoe",
name: "John Doe",
email: "john@example.com",
}).then((result) => {
expect(result.id).to.equal("johndoe");
expect(result.name).to.equal("John Doe");
expect(result.email).to.equal("john@example.com");
});
});

it("should update user data", async () => {
Users.save({
id: "markmaher",
name: "Mark Maher",
email: "mark@example.com",
}).then(() => {
Users.update("markmaher", {
name: "Marco Maher",
email: "marco@maher.com",
}).then((result) => {
expect(result.name).to.equal("Marco Maher");
expect(result.email).to.equal("marco@maher.com");
});
});
});

it("should delete user data", async () => {
Users.save({
id: "yousifsamir",
name: "Yousif Samir",
email: "yousif@samir.com",
}).then(() => {
Users.delete("yousifsamir").then(() => {
Users.find("yousifsamir").then((result) => {
expect(result).to.be.null;
});
});
});
});

it("should find user data by ID", async () => {
Users.save({
id: "alicejohnson",
name: "Alice Johnson",
email: "alice@example.com",
}).then((savedUser) => {
Users.find("alicejohnson").then((result) => {
expect(result.id).to.equal(savedUser.id);
expect(result.name).to.equal(savedUser.name);
expect(result.email).to.equal(savedUser.email);
});
});
});

it("should find all Users", async () => {
const users = [
{
id: () => "userOne1",
name: () => "User One",
email: () => "userOne@example.com",
},
{
id: () => "userTwo",
name: () => "User Two",
email: () => "userTwo@example.com",
},
];

for (const user of users) {
await Users.save({
id: user.id(), // Note: invoking the function here
name: user.name(), // Note: invoking the function here
email: user.email(), // Note: invoking the function here
});
}

const allUsers = await Users.findAll();

expect(allUsers).to.have.lengthOf.at.least(users.length);
expect(allUsers.every((user) => user.id && user.name && user.email)).to.be
.true;
});

after(async () => {
// Delete test data and logs folders after all tests have run
const testDataPath = path.join(__dirname, "data");
Expand Down Expand Up @@ -111,4 +170,4 @@ describe("jsonverse package", () => {
console.error("Error deleting test folders:", error);
}
});
});
});
Loading

0 comments on commit 5aa1813

Please sign in to comment.