2017-07-30 18:09:13 +08:00
|
|
|
// Flags: --expose-internals
|
2018-12-20 14:35:58 +08:00
|
|
|
|
|
|
|
// This tests interoperability between TextEncoder and TextDecoder with
|
|
|
|
// Node.js util.inspect and Buffer APIs
|
|
|
|
|
2017-07-30 18:09:13 +08:00
|
|
|
'use strict';
|
|
|
|
|
2019-12-25 18:02:16 +01:00
|
|
|
require('../common');
|
2017-10-02 14:42:55 -07:00
|
|
|
|
2017-07-30 18:09:13 +08:00
|
|
|
const assert = require('assert');
|
|
|
|
const { customInspectSymbol: inspect } = require('internal/util');
|
|
|
|
|
|
|
|
const encoded = Buffer.from([0xef, 0xbb, 0xbf, 0x74, 0x65,
|
|
|
|
0x73, 0x74, 0xe2, 0x82, 0xac]);
|
|
|
|
|
|
|
|
// Make Sure TextEncoder exists
|
|
|
|
assert(TextEncoder);
|
|
|
|
|
|
|
|
// Test TextEncoder
|
2017-10-02 14:42:55 -07:00
|
|
|
{
|
|
|
|
const enc = new TextEncoder();
|
|
|
|
assert.strictEqual(enc.encoding, 'utf-8');
|
|
|
|
assert(enc);
|
|
|
|
const buf = enc.encode('\ufefftest€');
|
|
|
|
assert.strictEqual(Buffer.compare(buf, encoded), 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
{
|
|
|
|
const enc = new TextEncoder();
|
|
|
|
const buf = enc.encode();
|
|
|
|
assert.strictEqual(buf.length, 0);
|
|
|
|
}
|
2017-07-30 18:09:13 +08:00
|
|
|
|
2017-10-02 14:42:55 -07:00
|
|
|
{
|
|
|
|
const enc = new TextEncoder();
|
|
|
|
const buf = enc.encode(undefined);
|
|
|
|
assert.strictEqual(buf.length, 0);
|
|
|
|
}
|
2017-07-30 18:09:13 +08:00
|
|
|
|
|
|
|
{
|
2018-01-13 22:05:26 +09:00
|
|
|
const inspectFn = TextEncoder.prototype[inspect];
|
|
|
|
const encodeFn = TextEncoder.prototype.encode;
|
|
|
|
const encodingGetter =
|
|
|
|
Object.getOwnPropertyDescriptor(TextEncoder.prototype, 'encoding').get;
|
|
|
|
|
|
|
|
const instance = new TextEncoder();
|
|
|
|
|
|
|
|
const expectedError = {
|
|
|
|
code: 'ERR_INVALID_THIS',
|
2019-12-25 18:02:16 +01:00
|
|
|
name: 'TypeError',
|
2018-01-13 22:05:26 +09:00
|
|
|
message: 'Value of "this" must be of type TextEncoder'
|
|
|
|
};
|
|
|
|
|
2018-02-09 02:32:04 +01:00
|
|
|
inspectFn.call(instance, Infinity, {});
|
|
|
|
encodeFn.call(instance);
|
|
|
|
encodingGetter.call(instance);
|
2018-01-13 22:05:26 +09:00
|
|
|
|
|
|
|
const invalidThisArgs = [{}, [], true, 1, '', new TextDecoder()];
|
2023-11-19 21:29:56 +01:00
|
|
|
for (const i of invalidThisArgs) {
|
2019-12-25 18:02:16 +01:00
|
|
|
assert.throws(() => inspectFn.call(i, Infinity, {}), expectedError);
|
|
|
|
assert.throws(() => encodeFn.call(i), expectedError);
|
|
|
|
assert.throws(() => encodingGetter.call(i), expectedError);
|
2023-11-19 21:29:56 +01:00
|
|
|
}
|
2017-07-30 18:09:13 +08:00
|
|
|
}
|