-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathapply.test.js
More file actions
82 lines (67 loc) · 2.13 KB
/
apply.test.js
File metadata and controls
82 lines (67 loc) · 2.13 KB
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
import apply from './apply';
describe('Function.prototype.apply', () => {
Function.prototype._apply = apply;
it('change the direction of this', () => {
const foo = {
value: 1,
};
function bar() {
return this.value;
}
// 和原生的 apply 操作进行比较验证
expect(bar._apply(foo)).toBe(bar.apply(foo));
});
it('change the direction of this, use in constructor', () => {
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.apply(this, [name, price]);
this.category = 'food';
}
function Food2(name, price) {
Product._apply(this, [name, price]);
this.category = 'food';
}
// 和原生的 apply 操作进行比较验证
expect(new Food('cheese', 5).name).toBe(new Food2('cheese', 5).name);
});
it('when \'this\' argument is null or undefined', () => {
window.value = 2;
function bar() {
return this.value;
}
// 非严格模式下的结果,严格模式下会报错
expect(bar._apply(null)).toBe(2);
expect(bar._apply(undefined)).toBe(2);
});
it('when \'this\' is other primitive value, excute success', () => {
function bar() {
return this.length;
}
// 和原生的 apply 操作进行比较验证
expect(bar._apply('123')).toBe(bar.apply('123'));
});
it('when \'runArg\' is not array like object, will throw an error', () => {
const foo = {
value: 1,
};
function bar(name, age) {
return `${name}: ${age}`;
}
const excute = function () {
// 后面传入的参数不是一个类数组
bar._apply(foo, 'jack', 12);
};
expect(excute).toThrowError('CreateListFromArrayLike called on non-object');
});
it('when assgin multiple runArg, will only get the first one', () => {
const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply(null, numbers, [10, 11, 12]);
const max2 = Math.max._apply(null, numbers, [10, 11, 12]);
// 当后面传入多个数组参数时,只会取第一个数组参数
expect(max2).toBe(7);
expect(max2).toBe(max);
});
});