diff --git a/src/01-simple-tests/index.test.ts b/src/01-simple-tests/index.test.ts index fbbea85de..a84f949db 100644 --- a/src/01-simple-tests/index.test.ts +++ b/src/01-simple-tests/index.test.ts @@ -1,32 +1,42 @@ -// 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 result = simpleCalculator({ a: 5, b: 2, action: Action.Add }); + expect(result).toBe(7); }); test('should subtract two numbers', () => { - // Write your test here + const result = simpleCalculator({ a: 5, b: 2, action: Action.Subtract }); + expect(result).toBe(3); }); test('should multiply two numbers', () => { - // Write your test here + const result = simpleCalculator({ a: 5, b: 2, action: Action.Multiply }); + expect(result).toBe(10); }); test('should divide two numbers', () => { - // Write your test here + const result = simpleCalculator({ a: 5, b: 2, action: Action.Divide }); + expect(result).toBe(2.5); }); test('should exponentiate two numbers', () => { - // Write your test here + const result = simpleCalculator({ + a: 5, + b: 2, + action: Action.Exponentiate, + }); + expect(result).toBe(25); }); test('should return null for invalid action', () => { - // Write your test here + const result = simpleCalculator({ a: 5, b: 2, action: 'other' }); + expect(result).toBe(null); }); test('should return null for invalid arguments', () => { - // Write your test here + const result = simpleCalculator({ a: 5, b: 'string', action: Action.Add }); + expect(result).toBe(null); }); }); diff --git a/src/02-table-tests/index.test.ts b/src/02-table-tests/index.test.ts index 4f36e892e..7aa527444 100644 --- a/src/02-table-tests/index.test.ts +++ b/src/02-table-tests/index.test.ts @@ -1,17 +1,19 @@ -// 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: 5, b: 2, action: Action.Add, expected: 7 }, + { a: 5, b: 2, action: Action.Subtract, expected: 3 }, + { a: 5, b: 2, action: Action.Multiply, expected: 10 }, + { a: 5, b: 2, action: Action.Divide, expected: 2.5 }, + { a: 5, b: 2, action: Action.Exponentiate, expected: 25 }, + { a: 5, b: 2, action: 'other', expected: null }, + { a: 5, b: 'string', action: Action.Add, 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); +describe.each(testCases)('simpleCalculator', ({ a, b, action, expected }) => { + test(`should return ${expected} for ${a} ${action} ${b}`, () => { + const result = simpleCalculator({ a, b, action }); + + expect(result).toBe(expected); }); - // Consider to use Jest table tests API to test all cases above }); diff --git a/src/03-error-handling-async/index.test.ts b/src/03-error-handling-async/index.test.ts index 6e106a6d6..78436830d 100644 --- a/src/03-error-handling-async/index.test.ts +++ b/src/03-error-handling-async/index.test.ts @@ -1,30 +1,35 @@ -// 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 + await expect(resolveValue(10)).resolves.toBe(10); }); }); describe('throwError', () => { test('should throw error with provided message', () => { - // Write your test here + expect(() => throwError('message')).toThrow('message'); }); test('should throw error with default message if message is not provided', () => { - // Write your test here + expect(() => throwError()).toThrow('Oops!'); }); }); 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..fd1728a82 100644 --- a/src/04-test-class/index.test.ts +++ b/src/04-test-class/index.test.ts @@ -1,44 +1,94 @@ -// Uncomment the code below and write your tests -// import { getBankAccount } from '.'; +import { + BankAccount, + getBankAccount, + InsufficientFundsError, + SynchronizationFailedError, + TransferFailedError, +} from '.'; +import { random } from 'lodash'; + +jest.mock('lodash', () => ({ + ...jest.requireActual('lodash'), + random: jest.fn(), +})); describe('BankAccount', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + test('should create account with initial balance', () => { - // Write your test here + const account = getBankAccount(100); + + expect(account).toBeInstanceOf(BankAccount); + expect(account.getBalance()).toBe(100); }); test('should throw InsufficientFundsError error when withdrawing more than balance', () => { - // Write your test here + const account = getBankAccount(100); + expect(() => account.withdraw(101)).toThrow(InsufficientFundsError); }); test('should throw error when transferring more than balance', () => { - // Write your test here + const account = getBankAccount(100); + const destinationAccount = getBankAccount(200); + expect(() => account.transfer(101, destinationAccount)).toThrow( + InsufficientFundsError, + ); }); test('should throw error when transferring to the same account', () => { - // Write your test here + const account = getBankAccount(100); + expect(() => account.transfer(50, account)).toThrow(TransferFailedError); }); test('should deposit money', () => { - // Write your test here + const account = getBankAccount(100); + account.deposit(50); + expect(account.getBalance()).toBe(150); }); test('should withdraw money', () => { - // Write your test here + const account = getBankAccount(100); + account.withdraw(30); + expect(account.getBalance()).toBe(70); }); test('should transfer money', () => { - // Write your test here + const account = getBankAccount(100); + const destinationAccount = getBankAccount(200); + account.transfer(30, destinationAccount); + expect(account.getBalance()).toBe(70); + expect(destinationAccount.getBalance()).toBe(230); }); test('fetchBalance should return number in case if request did not failed', async () => { - // Write your tests here + const mockedRandom = jest.mocked(random); + mockedRandom.mockReturnValueOnce(30).mockReturnValueOnce(1); + const account = getBankAccount(100); + + const result = await account.fetchBalance(); + + expect(typeof result).toBe('number'); + expect(result).toBe(30); }); - test('should set new balance if fetchBalance returned number', async () => { - // Write your tests here + test('should set new balance if synchronizeBalance returned number', async () => { + const mockedRandom = jest.mocked(random); + mockedRandom.mockReturnValueOnce(30).mockReturnValueOnce(1); + const account = getBankAccount(100); + + await account.synchronizeBalance(); + expect(account.getBalance()).toBe(30); }); - test('should throw SynchronizationFailedError if fetchBalance returned null', async () => { - // Write your tests here + test('should throw SynchronizationFailedError if synchronizeBalance returned null', async () => { + const mockedRandom = jest.mocked(random); + mockedRandom.mockReturnValueOnce(30).mockReturnValueOnce(0); + const account = getBankAccount(100); + + await expect(account.synchronizeBalance()).rejects.toThrow( + SynchronizationFailedError, + ); }); }); diff --git a/src/05-partial-mocking/index.test.ts b/src/05-partial-mocking/index.test.ts index 9d8a66cbd..20447eed1 100644 --- a/src/05-partial-mocking/index.test.ts +++ b/src/05-partial-mocking/index.test.ts @@ -1,20 +1,43 @@ -// 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 { + ...originalModule, + mockOne: jest.fn(), + mockTwo: jest.fn(), + mockThree: jest.fn(), + }; }); describe('partial mocking', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + afterAll(() => { jest.unmock('./index'); }); test('mockOne, mockTwo, mockThree should not log into console', () => { - // Write your test here + const logSpy = jest.spyOn(console, 'log'); + + mockOne(); + expect(logSpy).not.toHaveBeenCalled(); + + logSpy.mockClear(); + mockTwo(); + expect(logSpy).not.toHaveBeenCalled(); + + logSpy.mockClear(); + mockThree(); + expect(logSpy).not.toHaveBeenCalled(); }); test('unmockedFunction should log into console', () => { - // Write your test here + const logSpy = jest.spyOn(console, 'log'); + unmockedFunction(); + expect(logSpy).toHaveBeenCalledTimes(1); }); }); diff --git a/src/06-mocking-node-api/index.test.ts b/src/06-mocking-node-api/index.test.ts index 8dc3afd79..10edcb8c0 100644 --- a/src/06-mocking-node-api/index.test.ts +++ b/src/06-mocking-node-api/index.test.ts @@ -1,21 +1,50 @@ -// Uncomment the code below and write your tests -// import { readFileAsynchronously, doStuffByTimeout, doStuffByInterval } from '.'; +import { existsSync } from 'fs'; +import { readFile } from 'fs/promises'; +import { join } from 'path'; +import { readFileAsynchronously, doStuffByTimeout, doStuffByInterval } from '.'; + +jest.mock('path', () => ({ + ...jest.requireActual('path'), + join: jest.fn(), +})); + +jest.mock('fs', () => ({ + existsSync: jest.fn(), +})); + +jest.mock('fs/promises', () => ({ + readFile: jest.fn(), +})); describe('doStuffByTimeout', () => { beforeAll(() => { jest.useFakeTimers(); }); + afterEach(() => { + jest.restoreAllMocks(); + }); + afterAll(() => { jest.useRealTimers(); }); test('should set timeout with provided callback and timeout', () => { - // Write your test here + const setTimeoutSpy = jest.spyOn(global, 'setTimeout'); + const testFn = jest.fn(); + + doStuffByTimeout(testFn, 10); + expect(setTimeoutSpy).toHaveBeenCalledWith(testFn, 10); }); test('should call callback only after timeout', () => { - // Write your test here + const testFn = jest.fn(); + + doStuffByTimeout(testFn, 5000); + expect(testFn).not.toHaveBeenCalled(); + + jest.runAllTimers(); + expect(testFn).toHaveBeenCalledTimes(1); }); }); @@ -24,29 +53,75 @@ describe('doStuffByInterval', () => { jest.useFakeTimers(); }); + afterEach(() => { + jest.restoreAllMocks(); + }); + afterAll(() => { + jest.clearAllTimers(); jest.useRealTimers(); }); test('should set interval with provided callback and timeout', () => { - // Write your test here + const setIntervalSpy = jest.spyOn(global, 'setInterval'); + const testFn = jest.fn(); + doStuffByInterval(testFn, 10); + expect(setIntervalSpy).toHaveBeenCalledWith(testFn, 10); }); test('should call callback multiple times after multiple intervals', () => { - // Write your test here + const testFn = jest.fn(); + doStuffByInterval(testFn, 1000); + expect(testFn).not.toHaveBeenCalledTimes(1); + + jest.runOnlyPendingTimers(); + expect(testFn).toHaveBeenCalledTimes(1); + jest.runOnlyPendingTimers(); + expect(testFn).toHaveBeenCalledTimes(2); + jest.runOnlyPendingTimers(); + expect(testFn).toHaveBeenCalledTimes(3); }); }); describe('readFileAsynchronously', () => { + const mockedJoin = jest.mocked(join); + const mockedExistsSync = jest.mocked(existsSync); + const mockedReadFile = jest.mocked(readFile); + + afterEach(() => { + jest.clearAllMocks(); + }); + test('should call join with pathToFile', async () => { - // Write your test here + const pathToFile = './test.txt'; + + mockedJoin.mockReturnValue('/full/path/to/test.txt'); + mockedExistsSync.mockReturnValue(false); + + await readFileAsynchronously(pathToFile); + expect(mockedJoin).toHaveBeenCalledTimes(1); + expect(mockedJoin).toHaveBeenCalledWith(expect.any(String), pathToFile); }); test('should return null if file does not exist', async () => { - // Write your test here + const pathToFile = './test.txt'; + + mockedJoin.mockReturnValue('/full/path/to/test.txt'); + mockedExistsSync.mockReturnValue(false); + + const result = await readFileAsynchronously(pathToFile); + expect(result).toBeNull(); }); test('should return file content if file exists', async () => { - // Write your test here + const pathToFile = './test.txt'; + const text = 'File content'; + + mockedJoin.mockReturnValue('/full/path/to/test.txt'); + mockedExistsSync.mockReturnValue(true); + mockedReadFile.mockResolvedValue(Buffer.from(text)); + + const result = await readFileAsynchronously(pathToFile); + expect(result).toEqual(text); }); }); diff --git a/src/07-mocking-lib-api/index.test.ts b/src/07-mocking-lib-api/index.test.ts index e1dd001ef..5566c2192 100644 --- a/src/07-mocking-lib-api/index.test.ts +++ b/src/07-mocking-lib-api/index.test.ts @@ -1,17 +1,44 @@ -// Uncomment the code below and write your tests -/* import axios from 'axios'; -import { throttledGetDataFromApi } from './index'; */ +import axios, { AxiosInstance } from 'axios'; +import { throttledGetDataFromApi } from './index'; + +jest.mock('axios'); +jest.mock('lodash', () => ({ + ...jest.requireActual('lodash'), + throttle: jest.fn((fn) => fn), +})); describe('throttledGetDataFromApi', () => { + const mockGet = jest.fn(); + const mockCreate = jest.mocked(axios.create); + + beforeEach(() => { + jest.clearAllMocks(); + mockGet.mockResolvedValue({ data: 'ok' }); + mockCreate.mockReturnValue({ get: mockGet } as unknown as AxiosInstance); + }); + test('should create instance with provided base url', async () => { - // Write your test here + const relativePath = '/posts/1'; + await throttledGetDataFromApi(relativePath); + + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ + baseURL: 'https://jsonplaceholder.typicode.com', + }), + ); + expect(mockCreate).toHaveBeenCalledTimes(1); }); test('should perform request to correct provided url', async () => { - // Write your test here + const relativePath = '/posts/1'; + await throttledGetDataFromApi(relativePath); + + expect(mockGet).toHaveBeenCalledWith(relativePath); + expect(mockGet).toHaveBeenCalledTimes(1); }); test('should return response data', async () => { - // Write your test here + const relativePath = '/posts/1'; + await expect(throttledGetDataFromApi(relativePath)).resolves.toEqual('ok'); }); }); diff --git a/src/08-snapshot-testing/__snapshots__/index.test.ts.snap b/src/08-snapshot-testing/__snapshots__/index.test.ts.snap new file mode 100644 index 000000000..1bb72dc39 --- /dev/null +++ b/src/08-snapshot-testing/__snapshots__/index.test.ts.snap @@ -0,0 +1,23 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`generateLinkedList should generate linked list from values 2 1`] = ` +{ + "next": { + "next": { + "next": { + "next": { + "next": { + "next": null, + "value": null, + }, + "value": 5, + }, + "value": 4, + }, + "value": 3, + }, + "value": 2, + }, + "value": 1, +} +`; diff --git a/src/08-snapshot-testing/index.test.ts b/src/08-snapshot-testing/index.test.ts index 67c345706..5a5a55825 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 linkedList = generateLinkedList([1, 2, 3, 4, 5]); + expect(linkedList).toStrictEqual({ + value: 1, + next: { + value: 2, + next: { + value: 3, + next: { + value: 4, + next: { + value: 5, + next: { + value: null, + next: null, + }, + }, + }, + }, + }, + }); }); - // Check match by comparison with snapshot test('should generate linked list from values 2', () => { - // Write your test here + const linkedList = generateLinkedList([1, 2, 3, 4, 5]); + expect(linkedList).toMatchSnapshot(); }); });