forked from jestjs/jest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc.test.ts
89 lines (68 loc) · 2.51 KB
/
calc.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
import {describe, expect, it, jest} from '@jest/globals';
import Memory from '../Memory';
import makeCalc from '../calc';
import sub from '../sub';
import sum from '../sum';
jest.mock('../Memory');
jest.mock('../sub');
jest.mock('../sum');
const mockSub = jest.mocked(sub);
const mockSum = jest.mocked(sum);
const MockMemory = jest.mocked(Memory);
describe('calc - mocks', () => {
const memory = new MockMemory();
it('returns result from subtract', () => {
mockSub.mockReturnValueOnce(0);
const calc = makeCalc(memory);
const result = calc('Sub', [2, 2]);
expect(result).toBe(0);
expect(mockSub).toHaveBeenCalledWith(2, 2);
});
it('returns result from sum', () => {
mockSum.mockReturnValueOnce(2);
const calc = makeCalc(memory);
const result = calc('Sum', [1, 1]);
expect(result).toBe(2);
expect(mockSum).toHaveBeenCalledWith(1, 1);
});
it('adds last result to memory', () => {
MockMemory.prototype.add.mockImplementationOnce(x => x);
mockSum.mockReturnValueOnce(2);
const calc = makeCalc(memory);
const sumResult = calc('Sum', [1, 1]);
const memoryResult = calc('MemoryAdd', []);
expect(sumResult).toBe(2);
expect(memoryResult).toBe(2);
expect(MockMemory.prototype.add).toHaveBeenCalledWith(2);
});
it('subtracts last result to memory', () => {
MockMemory.prototype.subtract.mockImplementationOnce(x => x);
mockSum.mockReturnValueOnce(2);
const calc = makeCalc(memory);
const sumResult = calc('Sum', [1, 1]);
const memoryResult = calc('MemorySub', []);
expect(sumResult).toBe(2);
expect(memoryResult).toBe(2);
expect(MockMemory.prototype.subtract).toHaveBeenCalledWith(2);
});
it('clears the memory', () => {
MockMemory.prototype.add.mockImplementationOnce(x => x);
mockSum.mockReturnValueOnce(2).mockReturnValueOnce(4);
const calc = makeCalc(memory);
const sumResult = calc('Sum', [1, 1]);
const memoryResult = calc('MemoryAdd', []);
const sumResult2 = calc('Sum', [2, 2]);
const clearResult = calc('MemoryClear', []);
expect(sumResult).toBe(2);
expect(memoryResult).toBe(2);
expect(sumResult2).toBe(4);
expect(clearResult).toBe(4);
expect(MockMemory.prototype.reset).toHaveBeenCalledTimes(1);
});
it('throws an error when invalid Op is passed', () => {
const calc = makeCalc(memory);
// @ts-expect-error
expect(() => calc('Multiply', [2, 3])).toThrow(new Error('Invalid op'));
});
});