mock.property(object, propertyName[, value])


  • object <Object> 正在模拟其值的对象。

    ¥object <Object> The object whose value is being mocked.

  • propertyName <string> | <symbol> object 上要模拟的属性的标识符。

    ¥propertyName <string> | <symbol> The identifier of the property on object to mock.

  • value <any> 用作 object[propertyName] 模拟值的可选值。默认值:原始属性值。

    ¥value <any> An optional value used as the mock value for object[propertyName]. Default: The original property value.

  • 返回:<Proxy> 模拟对象的代理。被模拟的对象包含一个特殊的 mock 属性,它是 MockPropertyContext 的一个实例,可用于检查和更改被模拟属性的行为。

    ¥Returns: <Proxy> A proxy to the mocked object. The mocked object contains a special mock property, which is an instance of MockPropertyContext, and can be used for inspecting and changing the behavior of the mocked property.

为对象的属性值创建一个模拟。这允许你跟踪和控制对特定属性的访问,包括读取(getter)或写入(setter)的次数,以及在模拟后恢复原始值。

¥Creates a mock for a property value on an object. This allows you to track and control access to a specific property, including how many times it is read (getter) or written (setter), and to restore the original value after mocking.

test('mocks a property value', (t) => {
  const obj = { foo: 42 };
  const prop = t.mock.property(obj, 'foo', 100);

  assert.strictEqual(obj.foo, 100);
  assert.strictEqual(prop.mock.accessCount(), 1);
  assert.strictEqual(prop.mock.accesses[0].type, 'get');
  assert.strictEqual(prop.mock.accesses[0].value, 100);

  obj.foo = 200;
  assert.strictEqual(prop.mock.accessCount(), 2);
  assert.strictEqual(prop.mock.accesses[1].type, 'set');
  assert.strictEqual(prop.mock.accesses[1].value, 200);

  prop.mock.restore();
  assert.strictEqual(obj.foo, 42);
});