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

还是在这里做正确的事情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)

最佳答案

如果您查看toBeInstanceOf implementation,您会看到instanceof用于检查,但是正如您在Mozilla docs中看到的那样,string primitive与从String派生的Object不同。
您的第一个变体是检查的正确方法:

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

09-29 22:58