【问题标题】:.toBeInstanceOf(String) on buffer.toString() in Jest tests?.toBeInstanceOf(String) 在 Jest 测试中的 buffer.toString() 上?
【发布时间】:2017-06-02 05:06:10
【问题描述】:

对于使用Buffer#toString() 创建的字符串,如何在 Jest 断言中使用 expect(str).toBeInstanceOf(String)

或者在这里expect(typeof str).toEqual('string') 是正确的做法吗?


详情:

这个测试用例,使用typeof,通过了:

it('should test a Buffer.toString() - typeof', () => {
  const buf = new Buffer('hello world');
  const str = buf.toString('hex');
  expect(buf).toBeInstanceOf(Buffer);
  expect(typeof str).toEqual('string');
  // expect(str).toBeInstanceOf(String);
});

但是,这个使用 .toBeInstanceOf() 的测试用例失败了:

it('should test a Buffer.toString()', () => {
  const buf = new Buffer('hello world');
  const str = buf.toString('hex');
  expect(buf).toBeInstanceOf(Buffer);
  // expect(typeof str).toEqual('string');
  expect(str).toBeInstanceOf(String);
});

这是它的 Jest 输出:

 FAIL  ./buffer.jest.js
  ● should test a Buffer.toString()

    expect(value).toBeInstanceOf(constructor)

    Expected value to be an instance of:
      "String"
    Received:
      "68656c6c6f20776f726c64"
    Constructor:
      "String"

      at Object.<anonymous>.it (password.jest.js:11:15)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at process._tickCallback (internal/process/next_tick.js:109:7)

【问题讨论】:

    标签: javascript node.js testing jestjs


    【解决方案1】:

    如果您查看toBeInstanceOf implementation,您会看到instanceof 用于检查,但正如您在Mozilla docs 中看到的那样,string primitive 与@987654325 不同@派生自Object

    您的第一个变体是正确的检查方法:

    expect(typeof str).toEqual('string');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 2018-11-02
      • 2020-03-20
      • 2020-09-05
      相关资源
      最近更新 更多