如何在 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/