1// Flags: --expose-internals 2 3// This tests interoperability between TextEncoder and TextDecoder with 4// Node.js util.inspect and Buffer APIs 5 6'use strict'; 7 8require('../common'); 9 10const assert = require('assert'); 11const { customInspectSymbol: inspect } = require('internal/util'); 12 13const encoded = Buffer.from([0xef, 0xbb, 0xbf, 0x74, 0x65, 14 0x73, 0x74, 0xe2, 0x82, 0xac]); 15 16// Make Sure TextEncoder exists 17assert(TextEncoder); 18 19// Test TextEncoder 20{ 21 const enc = new TextEncoder(); 22 assert.strictEqual(enc.encoding, 'utf-8'); 23 assert(enc); 24 const buf = enc.encode('\ufefftest€'); 25 assert.strictEqual(Buffer.compare(buf, encoded), 0); 26} 27 28{ 29 const enc = new TextEncoder(); 30 const buf = enc.encode(); 31 assert.strictEqual(buf.length, 0); 32} 33 34{ 35 const enc = new TextEncoder(); 36 const buf = enc.encode(undefined); 37 assert.strictEqual(buf.length, 0); 38} 39 40{ 41 const inspectFn = TextEncoder.prototype[inspect]; 42 const encodeFn = TextEncoder.prototype.encode; 43 const encodingGetter = 44 Object.getOwnPropertyDescriptor(TextEncoder.prototype, 'encoding').get; 45 46 const instance = new TextEncoder(); 47 48 const expectedError = { 49 code: 'ERR_INVALID_THIS', 50 name: 'TypeError', 51 message: 'Value of "this" must be of type TextEncoder' 52 }; 53 54 inspectFn.call(instance, Infinity, {}); 55 encodeFn.call(instance); 56 encodingGetter.call(instance); 57 58 const invalidThisArgs = [{}, [], true, 1, '', new TextDecoder()]; 59 invalidThisArgs.forEach((i) => { 60 assert.throws(() => inspectFn.call(i, Infinity, {}), expectedError); 61 assert.throws(() => encodeFn.call(i), expectedError); 62 assert.throws(() => encodingGetter.call(i), expectedError); 63 }); 64} 65