示例工程 04-functions-this
04-functions-this/04-custom-bind/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
arrowTargetWithNew,
bindNonFunction,
fixedThisAndPartialArgs,
myBind,
newIgnoresContext,
run,
} from './main.js';
test('自定义 bind 与原生 bind 结果一致:固定 this + 预置参数', () => {
assert.deepEqual(fixedThisAndPartialArgs(), {
custom: 'Hello, Dr. Ada',
native: 'Hello, Dr. Ada',
});
});
test('new 调用时忽略 context,仍构造原类型的实例', () => {
assert.deepEqual(newIgnoresContext(), {
custom: '1,2',
native: '1,2',
customIsPoint: true,
nativeIsPoint: true,
});
});
test('bind 非函数抛 TypeError', () => {
assert.equal(bindNonFunction(), 'TypeError');
});
test('new 一个 bound 的箭头函数抛 TypeError', () => {
assert.equal(arrowTargetWithNew(), 'TypeError');
});
test('myBind 返回的是一个新函数', () => {
const f = () => 1;
const bound = myBind(f, null);
assert.notEqual(bound, f);
assert.equal(typeof bound, 'function');
});
test('run 输出 8 行场景与两条说明', () => {
const out = [];
const rows = run((s) => out.push(s));
assert.equal(rows.length, 8);
assert.equal(out.length, 11);
assert.equal(out[1], '自定义 bind:固定 this + 预置参数 => Hello, Dr. Ada');
assert.match(out.at(-1), /Reflect\.construct/);
});