Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
17 changes: 8 additions & 9 deletions src/01-simple-tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
// 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
expect(simpleCalculator({ a: 3, b: 2, action: Action.Add })).toBe(5);
});

test('should subtract two numbers', () => {
// Write your test here
expect(simpleCalculator({ a: 10, b: 4, action: Action.Subtract })).toBe(6);
});

test('should multiply two numbers', () => {
// Write your test here
expect(simpleCalculator({ a: 4, b: 3, action: Action.Multiply })).toBe(12);
});

test('should divide two numbers', () => {
// Write your test here
expect(simpleCalculator({ a: 10, b: 2, action: Action.Divide })).toBe(5);
});

test('should exponentiate two numbers', () => {
// Write your test here
expect(simpleCalculator({ a: 2, b: 8, action: Action.Exponentiate })).toBe(256);
});

test('should return null for invalid action', () => {
// Write your test here
expect(simpleCalculator({ a: 5, b: 3, action: 'invalid' })).toBeNull();
});

test('should return null for invalid arguments', () => {
// Write your test here
expect(simpleCalculator({ a: 'five', b: 3, action: Action.Add })).toBeNull();
});
});
35 changes: 23 additions & 12 deletions src/02-table-tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
// 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 },
{ a: 10, b: 5, action: Action.Subtract, expected: 5 },
{ a: 8, b: 3, action: Action.Subtract, expected: 5 },
{ a: 1, b: 0, action: Action.Subtract, expected: 1 },
{ a: 3, b: 4, action: Action.Multiply, expected: 12 },
{ a: 5, b: 5, action: Action.Multiply, expected: 25 },
{ a: 0, b: 9, action: Action.Multiply, expected: 0 },
{ a: 10, b: 2, action: Action.Divide, expected: 5 },
{ a: 9, b: 3, action: Action.Divide, expected: 3 },
{ a: 2, b: 8, action: Action.Exponentiate, expected: 256 },
{ a: 3, b: 3, action: Action.Exponentiate, expected: 27 },
{ a: 1, b: 2, action: 'invalid', expected: null },
{ a: 'five', b: 3, 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);
});
// Consider to use Jest table tests API to test all cases above
test.each(testCases)(
'should return $expected when a=$a, b=$b, action=$action',
({ a, b, action, expected }) => {
expect(simpleCalculator({ a, b, action })).toBe(expected);
},
);
});
20 changes: 13 additions & 7 deletions src/03-error-handling-async/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,36 @@
// 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 result = await resolveValue(42);
expect(result).toBe(42);
});
});

describe('throwError', () => {
test('should throw error with provided message', () => {
// Write your test here
expect(() => throwError('Custom message')).toThrow('Custom 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);
});
});
56 changes: 44 additions & 12 deletions src/04-test-class/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,76 @@
// Uncomment the code below and write your tests
// import { getBankAccount } from '.';
import {
getBankAccount,
InsufficientFundsError,
TransferFailedError,
SynchronizationFailedError,
} from '.';
import { random } from 'lodash';

// auto-mock lodash so random() is a jest.fn() we can control
jest.mock('lodash');

describe('BankAccount', () => {
test('should create account with initial balance', () => {
// Write your test here
const account = getBankAccount(100);
expect(account.getBalance()).toBe(100);
});

test('should throw InsufficientFundsError error when withdrawing more than balance', () => {
// Write your test here
const account = getBankAccount(50);
expect(() => account.withdraw(100)).toThrow(InsufficientFundsError);
});

test('should throw error when transferring more than balance', () => {
// Write your test here
const from = getBankAccount(50);
const to = getBankAccount(0);
expect(() => from.transfer(100, to)).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 from = getBankAccount(100);
const to = getBankAccount(0);
from.transfer(50, to);
expect(from.getBalance()).toBe(50);
expect(to.getBalance()).toBe(50);
});

test('fetchBalance should return number in case if request did not failed', async () => {
// Write your tests here
const account = getBankAccount(0);
// first random() → balance value; second random() → 1 (1 !== 0, so requestFailed=false)
(random as jest.Mock).mockReturnValueOnce(50).mockReturnValueOnce(1);
const balance = await account.fetchBalance();
expect(balance).toBe(50);
});

test('should set new balance if fetchBalance returned number', async () => {
// Write your tests here
const account = getBankAccount(0);
jest.spyOn(account, 'fetchBalance').mockResolvedValueOnce(75);
await account.synchronizeBalance();
expect(account.getBalance()).toBe(75);
});

test('should throw SynchronizationFailedError if fetchBalance returned null', async () => {
// Write your tests here
const account = getBankAccount(0);
jest.spyOn(account, 'fetchBalance').mockResolvedValueOnce(null);
await expect(account.synchronizeBalance()).rejects.toThrow(
SynchronizationFailedError,
);
});
});
22 changes: 17 additions & 5 deletions src/05-partial-mocking/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
// 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<typeof import('./index')>('./index');
const originalModule =
jest.requireActual<typeof import('./index')>('./index');
return {
...originalModule,
mockOne: jest.fn(),
mockTwo: jest.fn(),
mockThree: jest.fn(),
};
});

describe('partial mocking', () => {
Expand All @@ -11,10 +17,16 @@ describe('partial mocking', () => {
});

test('mockOne, mockTwo, mockThree should not log into console', () => {
// Write your test here
const consoleSpy = jest.spyOn(console, 'log');
mockOne();
mockTwo();
mockThree();
expect(consoleSpy).not.toHaveBeenCalled();
});

test('unmockedFunction should log into console', () => {
// Write your test here
const consoleSpy = jest.spyOn(console, 'log');
unmockedFunction();
expect(consoleSpy).toHaveBeenCalledWith('I am not mocked');
});
});
59 changes: 50 additions & 9 deletions src/06-mocking-node-api/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
// Uncomment the code below and write your tests
// import { readFileAsynchronously, doStuffByTimeout, doStuffByInterval } from '.';
import { readFileAsynchronously, doStuffByTimeout, doStuffByInterval } from '.';
import path from 'path';
import fs from 'fs';
import fsPromises from 'fs/promises';

// native Node.js module properties are non-configurable — must mock at module level
jest.mock('path', () => ({
...jest.requireActual<typeof import('path')>('path'),
join: jest.fn((...args: string[]) =>
jest.requireActual<typeof import('path')>('path').join(...args),
),
}));

jest.mock('fs', () => ({
existsSync: jest.fn(),
}));

jest.mock('fs/promises', () => ({
readFile: jest.fn(),
}));

describe('doStuffByTimeout', () => {
beforeAll(() => {
Expand All @@ -11,11 +29,18 @@ describe('doStuffByTimeout', () => {
});

test('should set timeout with provided callback and timeout', () => {
// Write your test here
const callback = jest.fn();
const timeoutSpy = jest.spyOn(global, 'setTimeout');
doStuffByTimeout(callback, 1000);
expect(timeoutSpy).toHaveBeenCalledWith(callback, 1000);
});

test('should call callback only after timeout', () => {
// Write your test here
const callback = jest.fn();
doStuffByTimeout(callback, 1000);
expect(callback).not.toHaveBeenCalled();
jest.runAllTimers();
expect(callback).toHaveBeenCalledTimes(1);
});
});

Expand All @@ -29,24 +54,40 @@ describe('doStuffByInterval', () => {
});

test('should set interval with provided callback and timeout', () => {
// Write your test here
const callback = jest.fn();
const intervalSpy = jest.spyOn(global, 'setInterval');
doStuffByInterval(callback, 1000);
expect(intervalSpy).toHaveBeenCalledWith(callback, 1000);
});

test('should call callback multiple times after multiple intervals', () => {
// Write your test here
const callback = jest.fn();
doStuffByInterval(callback, 1000);
expect(callback).not.toHaveBeenCalled();
jest.advanceTimersByTime(3000);
expect(callback).toHaveBeenCalledTimes(3);
});
});

describe('readFileAsynchronously', () => {
test('should call join with pathToFile', async () => {
// Write your test here
(fs.existsSync as jest.Mock).mockReturnValue(false);
await readFileAsynchronously('test.txt');
expect(path.join).toHaveBeenCalledWith(expect.any(String), 'test.txt');
});

test('should return null if file does not exist', async () => {
// Write your test here
(fs.existsSync as jest.Mock).mockReturnValue(false);
const result = await readFileAsynchronously('nonexistent.txt');
expect(result).toBeNull();
});

test('should return file content if file exists', async () => {
// Write your test here
(fs.existsSync as jest.Mock).mockReturnValue(true);
(fsPromises.readFile as jest.Mock).mockResolvedValue(
Buffer.from('file content'),
);
const result = await readFileAsynchronously('existing.txt');
expect(result).toBe('file content');
});
});
37 changes: 31 additions & 6 deletions src/07-mocking-lib-api/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,42 @@
// Uncomment the code below and write your tests
/* import axios from 'axios';
import { throttledGetDataFromApi } from './index'; */
import axios from 'axios';
import { throttledGetDataFromApi } from './index';

// bypass lodash throttle so every call goes through (no time-based skipping)
jest.mock('lodash', () => ({
...jest.requireActual<typeof import('lodash')>('lodash'),
throttle: jest.fn((fn: unknown) => fn),
}));

jest.mock('axios');

describe('throttledGetDataFromApi', () => {
test('should create instance with provided base url', async () => {
// Write your test here
const mockGet = jest.fn().mockResolvedValue({ data: {} });
(axios.create as jest.Mock).mockReturnValue({ get: mockGet });

await throttledGetDataFromApi('/todos/1');

expect(axios.create).toHaveBeenCalledWith({
baseURL: 'https://jsonplaceholder.typicode.com',
});
});

test('should perform request to correct provided url', async () => {
// Write your test here
const mockGet = jest.fn().mockResolvedValue({ data: {} });
(axios.create as jest.Mock).mockReturnValue({ get: mockGet });

await throttledGetDataFromApi('/todos/1');

expect(mockGet).toHaveBeenCalledWith('/todos/1');
});

test('should return response data', async () => {
// Write your test here
const responseData = { id: 1, title: 'Test todo' };
const mockGet = jest.fn().mockResolvedValue({ data: responseData });
(axios.create as jest.Mock).mockReturnValue({ get: mockGet });

const result = await throttledGetDataFromApi('/todos/1');

expect(result).toEqual(responseData);
});
});
Loading