This commit is contained in:
miqlangelo 2025-05-07 14:39:53 +02:00
parent ba20e7ea18
commit f0ab8640b3
34 changed files with 4420 additions and 0 deletions

3
src/12-testing/.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"deno.enable": true
}

View File

View File

@ -0,0 +1,15 @@
import { User } from '../types/index.ts';
export class ApiService {
fetchUser(id: number): Promise<User> {
return new Promise((resolve) =>
setTimeout(() => resolve({ id, username: 'Test User' }), 100)
);
}
fetchAllUsers(): Promise<User[]> {
return new Promise((resolve) =>
setTimeout(() => resolve([{ id: 1, username: 'User 1' }]), 100)
);
}
}

View File

@ -0,0 +1,16 @@
export class AuthService {
private loggedInUser: string | null = null;
login(username: string) {
if (!username) throw new Error('Username is required');
this.loggedInUser = username;
}
logout() {
this.loggedInUser = null;
}
isLoggedIn() {
return this.loggedInUser !== null;
}
}

View File

@ -0,0 +1,15 @@
import { User } from '../types/index.ts';
import { ApiService } from './ApiService.ts';
export class UserService {
constructor(private apiService: ApiService) {}
getUserById(id: number): Promise<User> {
if (!id) throw new Error('ID is required');
return this.apiService.fetchUser(id);
}
getAllUsers(): Promise<User[]> {
return this.apiService.fetchAllUsers();
}
}

View File

@ -0,0 +1,4 @@
export interface User {
id: number;
username: string;
}

View File

@ -0,0 +1,8 @@
export function sum(a: number, b: number): number {
return a + b;
}
export function divide(a: number, b: number): number {
if (b === 0) throw new Error('Division by zero');
return a / b;
}

View File

@ -0,0 +1,3 @@
export function isValidEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

View File

@ -0,0 +1,31 @@
// import { assertEquals, assertThrows } from 'jsr:@std/assert';
// import { AuthService } from '../../src/services/AuthService.ts';
Deno.test('AuthService - login should set the logged-in user', () => {
// TODO: Schreibe den Test
});
Deno.test(
'AuthService - login should throw an error if username is missing',
() => {
// TODO: Schreibe den Test
}
);
Deno.test('AuthService - logout should clear the logged-in user', () => {
// TODO: Schreibe den Test
});
Deno.test(
'AuthService - isLoggedIn should return true if a user is logged in',
() => {
// TODO: Schreibe den Test
}
);
Deno.test(
'AuthService - isLoggedIn should return false if no user is logged in',
() => {
// TODO: Schreibe den Test
}
);

View File

@ -0,0 +1,21 @@
// import { assertEquals, assertThrows } from 'jsr:@std/assert';
// import { UserService } from '../../src/services/UserService.ts';
// import { ApiService } from '../../src/services/ApiService.ts';
Deno.test('UserService - getUserById should return a user', async () => {
// TODO: Schreibe den Test
});
Deno.test(
'UserService - getUserById should throw an error if ID is missing',
async () => {
// TODO: Schreibe den Test
}
);
Deno.test(
'UserService - getAllUsers should return a list of users',
async () => {
// TODO: Schreibe den Test
}
);

View File

@ -0,0 +1,20 @@
// import { assertEquals, assertThrows } from 'jsr:@std/assert';
// import { sum, divide } from '../../src/utils/math.ts';
Deno.test('math utils - sum should return the sum of two numbers', () => {
// TODO: Schreibe den Test
});
Deno.test(
'math utils - divide should return the quotient of two numbers',
() => {
// TODO: Schreibe den Test
}
);
Deno.test(
'math utils - divide should throw an error when dividing by zero',
() => {
// TODO: Schreibe den Test
}
);

View File

@ -0,0 +1,16 @@
// import { assertEquals } from 'jsr:@std/assert';
// import { isValidEmail } from '../../src/utils/validation.ts';
Deno.test(
'validation utils - isValidEmail should return true for valid emails',
() => {
// TODO: Schreibe den Test
}
);
Deno.test(
'validation utils - isValidEmail should return false for invalid emails',
() => {
// TODO: Schreibe den Test
}
);

View File

@ -0,0 +1,30 @@
import { beforeEach, describe, test } from '@jest/globals';
import { AuthService } from '../../src/services/AuthService.ts';
describe('AuthService', () => {
let authService: AuthService;
beforeEach(() => {
// TODO: Initialisiere AuthService
});
test('login should set the logged-in user', () => {
// TODO: Schreibe den Test
});
test('login should throw an error if username is missing', () => {
// TODO: Schreibe den Test
});
test('logout should clear the logged-in user', () => {
// TODO: Schreibe den Test
});
test('isLoggedIn should return true if a user is logged in', () => {
// TODO: Schreibe den Test
});
test('isLoggedIn should return false if no user is logged in', () => {
// TODO: Schreibe den Test
});
});

View File

@ -0,0 +1,24 @@
// import { beforeEach, describe, test, jest, expect } from '@jest/globals';
// import { ApiService } from '../../src/services/ApiService.ts';
// import { UserService } from '../../src/services/UserService.ts';
describe('UserService', () => {
let userService: UserService;
let apiService: ApiService;
beforeEach(() => {
// TODO: Erstelle Mocks/Stubs für ApiService
});
test('getUserById should return a user', async () => {
// TODO: Schreibe den Test
});
test('getUserById should throw an error if ID is missing', async () => {
// TODO: Schreibe den Test
});
test('getAllUsers should return a list of users', async () => {
// TODO: Schreibe den Test
});
});

View File

@ -0,0 +1,16 @@
import { describe, test } from '@jest/globals';
// import { sum, divide } from '../../src/utils/math.ts';
describe('math utils', () => {
test('sum should return the sum of two numbers', () => {
// TODO: Schreibe den Test
});
test('divide should return the quotient of two numbers', () => {
// TODO: Schreibe den Test
});
test('divide should throw an error when dividing by zero', () => {
// TODO: Schreibe den Test
});
});

View File

@ -0,0 +1,12 @@
import { describe, test } from '@jest/globals';
// import { isValidEmail } from '../../src/utils/validation.ts';
describe('validation utils', () => {
test('isValidEmail should return true for valid emails', () => {
// TODO: Schreibe den Test
});
test('isValidEmail should return false for invalid emails', () => {
// TODO: Schreibe den Test
});
});

35
src/12-testing/deno.lock generated Normal file
View File

@ -0,0 +1,35 @@
{
"version": "5",
"specifiers": {
"jsr:@std/assert@*": "1.0.11",
"jsr:@std/assert@^1.0.10": "1.0.11",
"jsr:@std/internal@^1.0.5": "1.0.5",
"jsr:@std/testing@*": "1.0.9"
},
"jsr": {
"@std/assert@1.0.11": {
"integrity": "2461ef3c368fe88bc60e186e7744a93112f16fd110022e113a0849e94d1c83c1",
"dependencies": [
"jsr:@std/internal"
]
},
"@std/internal@1.0.5": {
"integrity": "54a546004f769c1ac9e025abd15a76b6671ddc9687e2313b67376125650dc7ba"
},
"@std/testing@1.0.9": {
"integrity": "9bdd4ac07cb13e7594ac30e90f6ceef7254ac83a9aeaa089be0008f33aab5cd4",
"dependencies": [
"jsr:@std/assert@^1.0.10"
]
}
},
"workspace": {
"packageJson": {
"dependencies": [
"npm:@types/jest@^29.5.14",
"npm:jest@^29.7.0",
"npm:ts-jest@^29.3.2"
]
}
}
}

View File

@ -0,0 +1,8 @@
/** @type {import('ts-jest').JestConfigWithTsJest} **/
module.exports = {
testEnvironment: "node",
transform: {
"^.+\.tsx?$": ["ts-jest",{}],
},
testPathIgnorePatterns: ["<rootDir>/src/deno"]
};

3861
src/12-testing/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,17 @@
{
"name": "12-testing",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@types/jest": "^29.5.14",
"jest": "^29.7.0",
"ts-jest": "^29.3.2"
}
}

View File

@ -0,0 +1,7 @@
import { assertEquals } from 'jsr:@std/assert/equals';
import { fetchData } from '../fetch.ts';
Deno.test('Daten abrufen', async () => {
const data = await fetchData();
assertEquals(data, 'Daten empfangen');
});

View File

@ -0,0 +1,6 @@
import { assertEquals } from 'jsr:@std/assert';
import { add } from '../math.ts';
Deno.test('Addition von zwei Zahlen', () => {
assertEquals(add(1, 2), 3);
});

View File

@ -0,0 +1,19 @@
import { assertEquals } from 'jsr:@std/assert@^1.0.10/equals';
import { UserService } from '../user.service.ts';
Deno.test('getUserById should return a user', async (t) => {
await t.step('addUser should add a user to the list', () => {
const userService = new UserService();
userService.addUser('Sarah', 28);
const result = userService.getUsers().map((u) => u.name);
assertEquals(result, ['Sarah']);
});
await t.step('get Users should return an empty list', () => {
const userService = new UserService();
const result = userService.getUsers();
assertEquals(result, []);
});
});

View File

@ -0,0 +1,10 @@
import { assertThrows } from 'jsr:@std/assert/throws';
import { riskyFunction } from '../utils.ts';
Deno.test('Soll einen Fehler werfen', () => {
assertThrows(
() => riskyFunction(-100),
Error,
'Wert darf nicht negativ sein!'
);
});

View File

@ -0,0 +1,3 @@
export async function fetchData(): Promise<string> {
return new Promise(resolve => setTimeout(() => resolve("Daten empfangen"), 1000))
}

View File

@ -0,0 +1,5 @@
import { fetchData } from '../fetch';
test('Daten abrufen', async () => {
await expect(fetchData()).resolves.toBe('Daten empfangen');
});

View File

@ -0,0 +1,14 @@
import { add } from '../math';
test('Addition von zwei Zahlen', () => {
// Arrange
const a = 5;
const b = 3;
const expected = 8;
// Act
const result = add(a, b);
// Assert
expect(result).toBe(expected);
});

View File

@ -0,0 +1,56 @@
import { UserService } from '../user.service';
describe('User Service Add', () => {
let userService: UserService;
beforeEach(() => {
userService = new UserService();
jest
.spyOn(userService, 'getUserById')
.mockReturnValue({ id: 1337, name: 'Test User', age: 22 });
});
test('Test User Alice', () => {
userService.addUser('Alice');
const users = userService.getUsers();
expect(users).toHaveLength(1);
});
test('Test User Bob', () => {
const expected = [{ id: 1, name: 'Bob', age: 28 }];
userService.addUser('Bob');
const users = userService.getUsers();
expect(users).toEqual(expected);
});
test('getUserById should return a user', () => {
jest
.spyOn(userService, 'getUserById')
.mockReturnValue({ id: 1337, name: 'Test User', age: 22 });
const result = userService.getUserById(1);
expect(result?.id).toEqual(1337);
expect(userService.getUserById).toHaveBeenCalledTimes(1);
});
class FakeUserService {
getUserById(id: number) {
return { id, name: 'Fake User', age: 33 };
}
}
test('getUserById should return a fake user', () => {
const fakeUserService = new FakeUserService();
const result = fakeUserService.getUserById(123);
expect(result.id).toEqual(123);
});
});

View File

@ -0,0 +1,3 @@
export function add(a: number, b: number): number {
return a + b;
}

View File

@ -0,0 +1,22 @@
export type User = {
id: number;
name: string;
age: number;
};
export class UserService {
private users: User[] = [];
public addUser(name: string, age: number = 28) {
const id = this.users.length + 1;
this.users.push({ id, name, age });
}
public getUsers() {
return this.users;
}
public getUserById(id: number): User | undefined {
return this.users.find((u) => u.id === id);
}
}

View File

@ -0,0 +1,7 @@
export function riskyFunction(value: number) {
if (value < 0) {
throw new Error('Wert darf nicht negativ sein!');
}
return value;
}

View File

@ -0,0 +1,113 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "libReplacement": true, /* Enable lib replacement. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "ESNext" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
// "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}