diff --git a/src/01-simple-tests/index.test.ts b/src/01-simple-tests/index.test.ts index fbbea85de..c17a79429 100644 --- a/src/01-simple-tests/index.test.ts +++ b/src/01-simple-tests/index.test.ts @@ -1,32 +1,46 @@ -// Uncomment the code below and write your tests -// import { simpleCalculator, Action } from './index'; +import { simpleCalculator, Action } from './index'; describe('simpleCalculator tests', () => { test('should add two numbers', () => { - // Write your test here + const total = simpleCalculator({ a: 4, b: 2, action: Action.Add }); + expect(total).toBe(6); }); test('should subtract two numbers', () => { - // Write your test here + const total = simpleCalculator({ a: 4, b: 2, action: Action.Subtract }); + expect(total).toBe(2); }); test('should multiply two numbers', () => { - // Write your test here + const total = simpleCalculator({ a: 4, b: 2, action: Action.Multiply }); + expect(total).toBe(8); }); test('should divide two numbers', () => { - // Write your test here + const total = simpleCalculator({ a: 4, b: 2, action: Action.Divide }); + expect(total).toBe(2); }); test('should exponentiate two numbers', () => { - // Write your test here + const total = simpleCalculator({ a: 4, b: 2, action: Action.Exponentiate }); + expect(total).toBe(16); }); test('should return null for invalid action', () => { - // Write your test here + const total = simpleCalculator({ + a: 4, + b: 2, + action: '', + }); + expect(total).toBe(null); }); test('should return null for invalid arguments', () => { - // Write your test here + const total = simpleCalculator({ + a: '', + b: 2, + action: Action.Exponentiate, + }); + expect(total).toBe(null); }); }); diff --git a/src/02-table-tests/index.test.ts b/src/02-table-tests/index.test.ts index 4f36e892e..952227377 100644 --- a/src/02-table-tests/index.test.ts +++ b/src/02-table-tests/index.test.ts @@ -1,17 +1,23 @@ // Uncomment the code below and write your tests -/* import { simpleCalculator, Action } from './index'; +import { simpleCalculator, Action } from './index'; const testCases = [ - { a: 1, b: 2, action: Action.Add, expected: 3 }, - { a: 2, b: 2, action: Action.Add, expected: 4 }, - { a: 3, b: 2, action: Action.Add, expected: 5 }, - // continue cases for other actions -]; */ + { a: 1, b: 2, action: Action.Add, expected: 3 }, + { a: 2, b: 2, action: Action.Add, expected: 4 }, + { a: 3, b: 2, action: Action.Add, expected: 5 }, + // cases from previous test + { a: 4, b: 2, action: Action.Add, expected: 6 }, + { a: 4, b: 2, action: Action.Subtract, expected: 2 }, + { a: 4, b: 2, action: Action.Multiply, expected: 8 }, + { a: 4, b: 2, action: Action.Divide, expected: 2 }, + { a: 4, b: 2, action: Action.Exponentiate, expected: 16 }, + { a: 4, b: 2, action: '', expected: null }, + { a: '', b: 2, action: Action.Exponentiate, expected: null }, +]; describe('simpleCalculator', () => { - // This test case is just to run this test suite, remove it when you write your own tests - test('should blah-blah', () => { - expect(true).toBe(true); - }); // Consider to use Jest table tests API to test all cases above + test.each(testCases)('table tests', ({ a, b, action, expected }) => { + expect(simpleCalculator({ a, b, action })).toBe(expected); + }); }); diff --git a/src/03-error-handling-async/index.test.ts b/src/03-error-handling-async/index.test.ts index 6e106a6d6..73538ae05 100644 --- a/src/03-error-handling-async/index.test.ts +++ b/src/03-error-handling-async/index.test.ts @@ -1,30 +1,38 @@ -// Uncomment the code below and write your tests -// import { throwError, throwCustomError, resolveValue, MyAwesomeError, rejectCustomError } from './index'; +import { + throwError, + throwCustomError, + resolveValue, + MyAwesomeError, + rejectCustomError, +} from './index'; describe('resolveValue', () => { test('should resolve provided value', async () => { - // Write your test here + const value = 'hello'; + await expect(resolveValue(value)).resolves.toBe(value); }); }); describe('throwError', () => { test('should throw error with provided message', () => { - // Write your test here + const msg = 'error'; + expect(() => throwError(msg)).toThrow(msg); }); test('should throw error with default message if message is not provided', () => { - // Write your test here + const defaultMessage = 'Oops!'; + expect(() => throwError()).toThrow(defaultMessage); }); }); describe('throwCustomError', () => { test('should throw custom error', () => { - // Write your test here + expect(() => throwCustomError()).toThrow(MyAwesomeError); }); }); describe('rejectCustomError', () => { test('should reject custom error', async () => { - // Write your test here + await expect(rejectCustomError()).rejects.toThrow(MyAwesomeError); }); }); diff --git a/src/04-test-class/index.test.ts b/src/04-test-class/index.test.ts index 937490d82..d382e4401 100644 --- a/src/04-test-class/index.test.ts +++ b/src/04-test-class/index.test.ts @@ -1,44 +1,110 @@ -// Uncomment the code below and write your tests -// import { getBankAccount } from '.'; +import { + getBankAccount, + InsufficientFundsError, + SynchronizationFailedError, + TransferFailedError, +} from '.'; describe('BankAccount', () => { test('should create account with initial balance', () => { - // Write your test here + const initialBalance = 10; + const bankAccount = getBankAccount(initialBalance); + expect(bankAccount.getBalance()).toBe(initialBalance); }); test('should throw InsufficientFundsError error when withdrawing more than balance', () => { - // Write your test here + const initialBalance = 10; + const withdrawAmount = 15; + const bankAccount = getBankAccount(initialBalance); + + expect(() => bankAccount.withdraw(withdrawAmount)).toThrow( + InsufficientFundsError, + ); }); test('should throw error when transferring more than balance', () => { - // Write your test here + const initialBalance = 10; + const transferAmount = 15; + const fromBankAccount = getBankAccount(initialBalance); + const toBankAccount = getBankAccount(initialBalance); + + expect(() => + fromBankAccount.transfer(transferAmount, toBankAccount), + ).toThrow(InsufficientFundsError); }); test('should throw error when transferring to the same account', () => { - // Write your test here + const initialBalance = 0; + const transferAmount = 15; + const bankAccount = getBankAccount(initialBalance); + + expect(() => bankAccount.transfer(transferAmount, bankAccount)).toThrow( + TransferFailedError, + ); }); test('should deposit money', () => { - // Write your test here + const initialBalance = 10; + const depositAmount = 10; + const bankAccount = getBankAccount(initialBalance); + + expect(bankAccount.deposit(depositAmount).getBalance()).toEqual( + initialBalance + depositAmount, + ); }); test('should withdraw money', () => { - // Write your test here + const initialBalance = 10; + const withdrawAmount = 10; + const bankAccount = getBankAccount(initialBalance); + + expect(bankAccount.withdraw(withdrawAmount).getBalance()).toEqual( + initialBalance - withdrawAmount, + ); }); test('should transfer money', () => { - // Write your test here + const initialBalance = 10; + const bankAccount = getBankAccount(initialBalance); + const toAccount = getBankAccount(0); + + expect(bankAccount.transfer(10, toAccount).getBalance()).toBe(0); }); test('fetchBalance should return number in case if request did not failed', async () => { - // Write your tests here + const initialBalance = 10; + const bankAccount = getBankAccount(initialBalance); + + expect(bankAccount.fetchBalance()).resolves.toBeDefined(); }); test('should set new balance if fetchBalance returned number', async () => { - // Write your tests here + const initialBalance = 10; + const newBalance = 10; + const bankAccount = getBankAccount(initialBalance); + + // Mock the method not assigned it + const fetchBalanceSpy = jest.spyOn(bankAccount, 'fetchBalance'); + + // bankAccount.fetchBalance = () => Promise.resolve(newBalance); + // const balance = await bankAccount.fetchBalance(); + // if (balance) { + // await expect(bankAccount.getBalance()).toBe(balance); + // } + await bankAccount.synchronizeBalance(); + expect(bankAccount.getBalance()).toEqual(newBalance); }); test('should throw SynchronizationFailedError if fetchBalance returned null', async () => { - // Write your tests here + const initialBalance = 10; + const bankAccount = getBankAccount(initialBalance); + + const balance = await bankAccount.fetchBalance(); + + if (!balance) { + await expect(() => bankAccount.synchronizeBalance).toThrow( + SynchronizationFailedError, + ); + } }); }); diff --git a/src/05-partial-mocking/index.test.ts b/src/05-partial-mocking/index.test.ts index 9d8a66cbd..be4c0cb29 100644 --- a/src/05-partial-mocking/index.test.ts +++ b/src/05-partial-mocking/index.test.ts @@ -1,8 +1,16 @@ -// Uncomment the code below and write your tests -// import { mockOne, mockTwo, mockThree, unmockedFunction } from './index'; +import { mockOne, mockTwo, mockThree, unmockedFunction } from './index'; jest.mock('./index', () => { - // const originalModule = jest.requireActual('./index'); + const originalModule = + jest.requireActual('./index'); + + return { + __esModule: true, + ...originalModule, + mockOne: jest.fn(), + mockTwo: jest.fn(), + mockThree: jest.fn(), + }; }); describe('partial mocking', () => { @@ -11,10 +19,27 @@ describe('partial mocking', () => { }); test('mockOne, mockTwo, mockThree should not log into console', () => { - // Write your test here + const consoleSpy = jest.spyOn(global.console, 'log'); + + mockOne(); + mockTwo(); + mockThree(); + expect(mockOne).toHaveBeenCalled(); + expect(mockTwo).toHaveBeenCalled(); + expect(mockThree).toHaveBeenCalled(); + + expect(consoleSpy).not.toHaveBeenCalled(); + consoleSpy.mockRestore(); }); test('unmockedFunction should log into console', () => { - // Write your test here + const consoleSpy = jest.spyOn(global.console, 'log'); + + unmockedFunction(); + + expect(consoleSpy).toHaveBeenCalled(); + expect(consoleSpy).toHaveBeenCalledTimes(1); + expect(consoleSpy).toHaveBeenCalledWith('I am not mocked'); + consoleSpy.mockRestore(); }); }); diff --git a/src/06-mocking-node-api/index.test.ts b/src/06-mocking-node-api/index.test.ts index 8dc3afd79..7a6ed740c 100644 --- a/src/06-mocking-node-api/index.test.ts +++ b/src/06-mocking-node-api/index.test.ts @@ -1,5 +1,11 @@ -// Uncomment the code below and write your tests -// import { readFileAsynchronously, doStuffByTimeout, doStuffByInterval } from '.'; +import fs from 'node:fs'; +import fsPromises from 'node:fs/promises'; +import path from 'node:path'; +import { doStuffByInterval, doStuffByTimeout, readFileAsynchronously } from '.'; + +const fileName = 'test.txt'; +jest.mock('fs'); +jest.mock('fs/promises'); describe('doStuffByTimeout', () => { beforeAll(() => { @@ -11,11 +17,27 @@ describe('doStuffByTimeout', () => { }); test('should set timeout with provided callback and timeout', () => { - // Write your test here + const callback = jest.fn(); + const timeout = 1000; + + jest.spyOn(global, 'setTimeout'); + + doStuffByTimeout(callback, timeout); + + expect(setTimeout).toHaveBeenCalledWith(callback, timeout); }); test('should call callback only after timeout', () => { - // Write your test here + const callback = jest.fn(); + const timeout = 1000; + + doStuffByTimeout(callback, timeout); + + expect(callback).not.toHaveBeenCalled(); + + jest.advanceTimersByTime(timeout); + + expect(callback).toHaveBeenCalled(); }); }); @@ -29,24 +51,56 @@ describe('doStuffByInterval', () => { }); test('should set interval with provided callback and timeout', () => { - // Write your test here + const callback = jest.fn(); + const timeout = 1000; + + jest.spyOn(global, 'setInterval'); + + doStuffByInterval(callback, timeout); + + expect(setInterval).toHaveBeenCalledWith(callback, timeout); }); test('should call callback multiple times after multiple intervals', () => { - // Write your test here + const callback = jest.fn(); + const interval = 1000; + + jest.spyOn(global, 'setInterval'); + + doStuffByInterval(callback, interval); + + expect(callback).toHaveBeenCalled(); + + jest.advanceTimersByTime(interval); + expect(callback).toHaveBeenCalledTimes(1); + + jest.advanceTimersByTime(interval); + expect(callback).toHaveBeenCalledTimes(2); }); }); describe('readFileAsynchronously', () => { test('should call join with pathToFile', async () => { - // Write your test here + const spy = jest.spyOn(path, 'join'); + + await readFileAsynchronously(fileName); + + expect(spy).toHaveBeenCalledWith(__dirname, fileName); }); test('should return null if file does not exist', async () => { - // Write your test here + jest.spyOn(fs, 'existsSync').mockReturnValue(false); + const fileContent = await readFileAsynchronously(fileName); + + expect(fileContent).toBeNull(); }); test('should return file content if file exists', async () => { - // Write your test here + const content = 'content'; + jest.spyOn(fs, 'existsSync').mockReturnValue(true); + jest.spyOn(fsPromises, 'readFile').mockResolvedValue(content); + + const fileContent = await readFileAsynchronously(fileName); + expect(fileContent).toBe(content); }); }); diff --git a/src/07-mocking-lib-api/index.test.ts b/src/07-mocking-lib-api/index.test.ts index e1dd001ef..9ab5c7e45 100644 --- a/src/07-mocking-lib-api/index.test.ts +++ b/src/07-mocking-lib-api/index.test.ts @@ -1,17 +1,40 @@ -// Uncomment the code below and write your tests -/* import axios from 'axios'; -import { throttledGetDataFromApi } from './index'; */ +import axios from 'axios'; +import { throttledGetDataFromApi } from './index'; + +jest.mock('lodash', () => ({ + throttle: jest.fn((fn) => fn), +})); + +jest.mock('axios', () => ({ + get: jest.fn().mockResolvedValue({ data: 'response' }), + create: function () { + return { + get: this.get.mockReturnValue({ data: 'response' }), + }; + }, +})); + +const newUrl = 'test'; +const baseUrl = 'https://jsonplaceholder.typicode.com'; describe('throttledGetDataFromApi', () => { test('should create instance with provided base url', async () => { - // Write your test here + const spy = jest.spyOn(axios, 'create'); + await throttledGetDataFromApi(newUrl); + + expect(spy).toHaveBeenCalledWith({ baseURL: baseUrl }); }); test('should perform request to correct provided url', async () => { - // Write your test here + const spy = jest.spyOn(axios.create(), 'get'); + await throttledGetDataFromApi(newUrl); + + expect(spy).toHaveBeenCalledWith(newUrl); }); test('should return response data', async () => { - // Write your test here + const responses = await throttledGetDataFromApi(newUrl); + + expect(responses).toBe('response'); }); }); diff --git a/src/08-snapshot-testing/index.test.ts b/src/08-snapshot-testing/index.test.ts index 67c345706..970b48632 100644 --- a/src/08-snapshot-testing/index.test.ts +++ b/src/08-snapshot-testing/index.test.ts @@ -1,14 +1,31 @@ // Uncomment the code below and write your tests -// import { generateLinkedList } from './index'; +import { generateLinkedList } from './index'; describe('generateLinkedList', () => { // Check match by expect(...).toStrictEqual(...) test('should generate linked list from values 1', () => { - // Write your test here + const array = ['roots', 'trunk', 'branches']; + + const checkTest = { + value: 'roots', + next: { + value: 'trunk', + next: { + value: 'branches', + next: { + value: null, + next: null, + }, + }, + }, + }; + + expect(generateLinkedList(array)).toStrictEqual(checkTest); }); // Check match by comparison with snapshot test('should generate linked list from values 2', () => { - // Write your test here + const array = ['head', 'neck', 'body', 'tail']; + expect(generateLinkedList(array)).toMatchSnapshot(); }); });