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: unit tests for utils functions #92

Merged
merged 9 commits into from
Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
3 changes: 3 additions & 0 deletions apps/dashboard/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": [["@babel/preset-env", { "targets": { "node": "current" } }]]
}
3 changes: 3 additions & 0 deletions apps/dashboard/babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }]]
};
210 changes: 210 additions & 0 deletions apps/dashboard/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
Toyin5 marked this conversation as resolved.
Show resolved Hide resolved
*/

import type { Config } from 'jest';

const config: Config = {
// All imported modules in your tests should be mocked automatically
// automock: false,

// Stop running tests after `n` failures
// bail: 0,

// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\User\\AppData\\Local\\Temp\\jest",

// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,

// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,

// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,

// The directory where Jest should output its coverage files
coverageDirectory: 'coverage'

// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],

// Indicates which provider should be used to instrument code for coverage
// coverageProvider: "babel",

// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],

// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,

// A path to a custom dependency extractor
// dependencyExtractor: undefined,

// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,

// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },

// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],

// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,

// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,

// A set of global variables that need to be available in all test environments
// globals: {},

// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",

// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],

// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],

// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],

// Activates notifications for test results
// notify: false,

// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",

// A preset that is used as a base for Jest's configuration
// preset: undefined,

// Run tests from one or more projects
// projects: undefined,

// Use this configuration option to add custom reporters to Jest
// reporters: undefined,

// Automatically reset mock state before every test
// resetMocks: false,

// Reset the module registry before running each individual test
// resetModules: false,

// A path to a custom resolver
// resolver: undefined,

// Automatically restore mock state and implementation before every test
// restoreMocks: false,

// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,

// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],

// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",

// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],

// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],

// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,

// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],

// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},

// Adds a location field to test results
// testLocationInResults: false,

// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],

// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],

// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],

// This option allows the use of a custom results processor
// testResultsProcessor: undefined,

// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",

// A map from regular expressions to paths to transformers
// transform: undefined,

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+$"
// ],

// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,

// Indicates whether each individual test should be reported during the run
// verbose: undefined,

// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],

// Whether to use watchman for file crawling
// watchman: true,
};

export default config;

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
transform: {
'^.+\\.svelte$': 'svelte-jester',
'^.+\\.ts$': 'ts-jest',
'\\.[jt]sx?$': 'babel-jest'
}
};
13 changes: 12 additions & 1 deletion apps/dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
"export": "vite build --entry \"/ /404 login signup forgot onboarding courses org lms course\"",
"postexport": "mv __sapper__/export/404/index.html __sapper__/export/404.html",
"start": "node build",
"prepare": "svelte-kit sync"
"prepare": "svelte-kit sync",
"test": "jest",
"test:watch": "pnpm run test --watch"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.386.0",
Expand Down Expand Up @@ -57,26 +59,35 @@
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/plugin-transform-runtime": "^7.22.9",
"@babel/preset-env": "^7.22.9",
"@babel/preset-typescript": "^7.23.3",
"@babel/runtime": "^7.22.6",
"@sveltejs/kit": "^1.22.4",
"@tailwindcss/typography": "^0.5.9",
"@testing-library/jest-dom": "^6.1.5",
"@testing-library/svelte": "^4.0.5",
"@types/jest": "^29.5.10",
"@types/lodash": "^4.14.196",
"@types/nodemailer": "^6.4.11",
"autoprefixer": "^10.4.14",
"babel-jest": "^29.7.0",
"carbon-components-svelte": "^0.79.0",
"carbon-icons-svelte": "^12.1.0",
"dotenv": "^16.3.1",
"eslint-config-custom": "workspace:*",
"jest": "^29.7.0",
"postcss": "^8.4.24",
"postcss-load-config": "^4.0.1",
"sass": "^1.64.2",
"supabase": "^1.112.0",
"svelte": "^4.1.2",
"svelte-calendar": "^3.1.6",
"svelte-dnd-action": "^0.9.24",
"svelte-jester": "^3.0.0",
"svelte-loading-spinners": "^0.3.4",
"svelte-preprocess": "^5.0.4",
"tailwindcss": "^3.3.2",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.2",
"tsconfig": "workspace:*",
"tslib": "^2.6.1",
"typescript": "^5.1.6",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script lang="ts">
import { browser } from '$app/environment';
import Modal from '$lib/components/Modal/index.svelte';
import TextField from '$lib/components/Form/TextField.svelte';
import PrimaryButton from '$lib/components/PrimaryButton/index.svelte';
Expand Down Expand Up @@ -98,7 +99,7 @@
}, 500);
}

$: note = getTextFromHTML($lesson?.materials?.note || '');
$: note = browser ? getTextFromHTML($lesson?.materials?.note || '') : '';
</script>

<Modal
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script lang="ts">
import { browser } from '$app/environment';
import isEmpty from 'lodash/isEmpty';
import { useCompletion } from 'ai/svelte';
import MODES from '$lib/utils/constants/mode.js';
Expand Down Expand Up @@ -84,7 +85,7 @@

if (!document) return false;

return getTextFromHTML(note) === '';
return browser ? getTextFromHTML(note) === '' : false;
}

function isMaterialsEmpty(materials: LessonPage['materials']) {
Expand Down
30 changes: 30 additions & 0 deletions apps/dashboard/src/lib/utils/functions/IsSubmissionEarly.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import isSubmissionEarly from './isSubmissionEarly';

describe('isSubmissionEarly', () => {
test('should return true when createdAt is earlier than dueDate', () => {
const due_date = Date.now();
Toyin5 marked this conversation as resolved.
Show resolved Hide resolved
const created_at = new Date('2023-12-15');
const result = isSubmissionEarly(created_at, due_date);
expect(result).toBe(true);
});

test('should return true when both created_at and due_date are null', () => {
const due_date = null;
const created_at = null;
const result = isSubmissionEarly(created_at, due_date);
expect(result).toBe(true);
});
test('should return true when created_at is the same as due_date', () => {
const due_date = new Date('2023-12-15');
const created_at = new Date('2023-12-15');
const result = isSubmissionEarly(created_at, due_date);
expect(result).toBe(true);
});

test('should return false when created_at is later than due_date', () => {
const due_date = new Date('2023-12-15');
const created_at = new Date('2023-12-16');
const result = isSubmissionEarly(created_at, due_date);
expect(result).toBe(false);
});
});
19 changes: 19 additions & 0 deletions apps/dashboard/src/lib/utils/functions/course.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import '@testing-library/jest-dom';
rotimi-best marked this conversation as resolved.
Show resolved Hide resolved
import { isCourseFree } from './course';

describe('course.ts', () => {
test('Should return True when cost is 0', () => {
const result = isCourseFree(0);
expect(result).toBeTruthy();
});

test('Should return true when cost is negative', () => {
const result = isCourseFree(-10);
expect(result).toBeTruthy();
});

test('Should return True when cost is Not A Number', () => {
const result = isCourseFree(NaN);
expect(result).toBeTruthy();
});
});
3 changes: 0 additions & 3 deletions apps/dashboard/src/lib/utils/functions/course.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { browser } from '$app/environment';
import type { Course } from '../types';

export const isCourseFree = (cost: number) => !(Number(cost) > 0);
Expand All @@ -19,8 +18,6 @@ export const getStudentInviteLink = (_course: Course, orgSiteName: string, origi
};

export const getTextFromHTML = (html: string): string => {
if (!browser) return html;

const dummyDiv = document.createElement('div');
dummyDiv.innerHTML = html;

Expand Down
37 changes: 37 additions & 0 deletions apps/dashboard/src/lib/utils/functions/date.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import '@testing-library/jest-dom';
Toyin5 marked this conversation as resolved.
Show resolved Hide resolved
import { calDateDiff, getGreeting } from './date';

describe('calDateDiff', () => {
test('should return the correct time difference when the input date is in the past', () => {
const inputDate = new Date('2022-01-01');
const expectedOutput = '2 years ago';

const result = calDateDiff(inputDate);

expect(result).toBe(expectedOutput);
});

test('should return the correct time difference when the input date is a number', () => {
const inputDate = new Date(1640995200000); // January 1, 2022
const expectedOutput = '2 years ago';

const result = calDateDiff(inputDate);

expect(result).toBe(expectedOutput);
});
});

describe('getGreeting', () => {
test("should return 'Good Morning' when the current time is before 12pm", () => {
jest.useFakeTimers().setSystemTime(new Date('2023-12-10T00:21:01.691Z'));
expect(getGreeting()).toBe('Good Morning');
});
test("should return 'Good Afternoon' when the current time is after 12pm", () => {
jest.useFakeTimers().setSystemTime(new Date('2023-12-10T14:21:01.691Z'));
expect(getGreeting()).toBe('Good Afternoon');
});
test("should return 'Good Evening' when the current time is after 6pm", () => {
jest.useFakeTimers().setSystemTime(new Date('2023-12-10T19:21:01.691Z'));
expect(getGreeting()).toBe('Good Evening');
});
});
Loading
Loading