如何在开玩笑的断言中使用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);
});
这是它的嘲笑输出:
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)
如果您查看了实现的tobeinstance,您会看到instanceof
用于检查,但是如您在Mozilla Docs中所示的那样,string primitive
与String
衍生自Object
。
您的第一个变体是检查的正确方法:
expect(typeof str).toEqual('string');