javascript - Jest 测试中 buffer.toString() 上的 .toBeInstanceOf(String)?

标签 javascript node.js testing jestjs

如何在 Jest 断言中对使用 Buffer#toString() 创建的字符串使用 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)

最佳答案

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

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

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

关于javascript - Jest 测试中 buffer.toString() 上的 .toBeInstanceOf(String)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44321179/

相关文章:

javascript - 表单数据不再起作用

javascript - 尝试使用 Puppeteer 抓取外部站点时出错

testing - 我可以在使用 nightwatch 的文件上传中使用 setValue 中的链接吗

javascript - jquery 自动完成与外部 json 源

javascript - 根据url参数设置下拉值

javascript - 如果父 div 由 jquery 动画,是否可以防止某些子元素动画?

javascript - 更新函数 javascript 和 mongodb

node.js - 在AWS中找不到模块 'extend' Lambda Node JS

ruby-on-rails - 尝试访问表中的链接时无法让 Cucumber 脚本通过

ruby-on-rails-3 - Rails 3 功能测试 : Can't mass-assign protected attributes: controller, 操作