How to use MockPipes method in ng-mocks

Best JavaScript code snippet using ng-mocks

test.js

Source:test.js Github

copy

Full Screen

1// Really shitty tests for back-end.2// Need to replace timeouts with actual query/answer logic.3var termkit = {4 version: 1,5 test: true,6};7require.paths.unshift('./socket.io-node/lib');8require.paths.unshift('.');9require.paths.unshift('shell');10require.paths.unshift('../Shared/');11var whenDone = require('misc').whenDone;12var EventEmitter = require("events").EventEmitter;13var router = require("router");14var processor = require("shell/processor");15var meta = require("shell/meta");16var reader = require("shell/reader");17var autocomplete = require("shell/autocomplete");18var misc = require("misc");19var grep = require("shell/builtin/grep");20var asserts = [];21function assert(condition, message) {22 asserts.push([ !!condition, message, ]);23}24var track = whenDone(function () {25 var total = 0, failed = 0;26 for (i in asserts) (function (assert) {27 !assert[0] && failed++;28 total++;29 console.log(assert[0] ? '[X]' : '[ ]', '', assert[1]);30 })(asserts[i]);31 console.log(total + " tests, " + failed + " failed.");32});33/**34 * Helper: simulate a client connection on the router.35 */36function mockClient(flow, callback) {37 var client = new EventEmitter();38 var messages = [], success = true, i;39 client.send = function (message) {40 messages.push(message);41 };42 client.disconnect = function (message) {43 success = false;44 };45 var r = new router.router(client);46 for (i in flow) (function (message) {47 setTimeout(function () {48 client.emit('message', message);49 }, i * 100);50 })(flow[i]);51 52 setTimeout(track(function () {53 callback(messages, success);54 r.disconnect();55 }), i * 100 + 500);56}57/**58 * Helper: run worker commands on a shell.59 */60function mockShell(flow, callback) {61 var messages = [], success = true, i = 0;62 var stdin = new EventEmitter(),63 stdout = new EventEmitter();64 stdout.write = function (data) {65 messages.push(JSON.parse(data.substring(0, data.length - 1)));66 };67 var p = new processor.processor(stdin, stdout);68 for (i in flow) (function (message) {69 setTimeout(function () {70 stdin.emit('data', JSON.stringify(message) + '\u0000');71 }, i * 100);72 })(flow[i]);73 setTimeout(track(function () {74 callback(messages, success);75 stdin.emit('end');76 }), i * 100 + 1000);77}78/**79 * Test termkit handshake.80 */81function testHandshake(assert) {82 mockClient([83 {},84 ], function (messages, success) {85 assert(messages.length == 1 && messages[0].termkit == "1" && true, "TermKit handshake found.");86 });87 mockClient([88 { termkit: ".", },89 ], function (messages, success) {90 assert(!success, "Invalid version string is rejected.");91 });92 mockClient([93 { termkit: "1", },94 ], function (messages, success) {95 assert(success, "Valid version string is accepted.");96 });97}98/**99 * Test session/shell handling.100 */101function testSession(assert) {102 mockClient([103 { termkit: "1" },104 { query: 1, method: "session.open.shell" },105 { query: 2, method: "session.open.shell" },106 { query: 3, method: "shell.environment", session: 1, args: { } },107 { query: 4, method: "shell.environment", session: 2, args: { } },108 { query: 5, method: "session.close", session: 1 },109 { query: 6, method: "session.close", session: 2 },110 ], function (messages, success) {111 console.log(messages);112 assert(messages[1].success && messages[1].args.session == 1 &&113 messages[2].success && messages[2].args.session == 2, "Open shell session x2");114 assert(messages[3].success && messages[3].args && messages[3].args.cwd &&115 messages[4].success && messages[4].args && messages[4].args.cwd, "Environment is set x2");116 assert(messages[5].success && messages[6].success, "Close shell session x2");117 });118}119/**120 * Test command handling.121 */122function testCommands(assert) {123 mockShell([124// { query: 5, method: 'shell.run', args: { tokens: [ 'pwd' ], ref: 7 } },125 { query: 5, method: 'shell.run', args: { tokens: [ 'cat', 'test.js' ], ref: 4 } },126 ], function (messages, success) {127 /*128 for (i in messages) { 129 console.log(messages[i]);130 messages[i].args && messages[i].args.objects && console.log('Objects', messages[i].args.objects);131 }132 */133 var last = messages[messages.length - 1];134 assert(last.success && last.answer == 5, "Run single command");135 });136}137/**138 * Test mime-type handling.139 */140function testMeta(assert) {141 var headers, set, string;142 143 // Test basic getters and setters.144 headers = new meta.headers();145 146 headers.set('Content-Type', 'text/plain');147 assert(headers.get('Content-Type') == 'text/plain', 'Value getter/setter');148 headers.set('Content-Type', 'charset', 'utf-8');149 assert(headers.get('Content-Type', 'charset') == 'utf-8', 'Param getter/setter');150 headers.set('Content-Type', [ 'text/html', { 'charset': 'iso-8859-1' } ]);151 assert(headers.get('Content-Type') == 'text/html' &&152 headers.get('Content-Type', 'charset') == 'iso-8859-1', 'Combined getter/setter');153 154 // Test multiple value getters/setters.155 headers.set('Accept-Encoding', [ 'compress', 'gzip' ]);156 set = headers.get('Accept-Encoding');157 assert(set.length == 2 &&158 set[0] == 'compress' &&159 set[1] == 'gzip',160 'Multi-value getter/setter');161 headers.set('Accept', [162 [ 'text/html', { 'q': 1 } ],163 [ 'text/css' ],164 [ 'text/plain', { 'q': 0.8 } ],165 ] );166 set = headers.get('Accept');167 assert(set.length == 3 &&168 set[0] == 'text/html' &&169 set[1] == 'text/css' &&170 set[2] == 'text/plain',171 'Multi-value getter/setter combined');172 set = headers.get('Accept', 'q');173 assert(set.length == 3 &&174 set[0] == 1 &&175 typeof set[1] == 'undefined' &&176 set[2] == 0.8,177 'Multi-param getter/setter combined');178 // Test parsing rules of RFC 822 values.179 headers = new meta.headers();180 assert(headers.parseValue('"application/javascript"') == 'application/javascript',181 "Parse quoted value");182 assert(headers.parseValue('"app\\"li\\\\cati\\on\\/javascript"') == 'app"li\\cation/javascript',183 "Parse quoted value with escapes");184 set = headers.parseValue('max-age=0', true);185 assert(set[0] == null && typeof set[1] == 'object' && set[1]['max-age'] == '0',186 "Parse param");187 set = headers.parseValue('application/javascript;charset=utf-8', true);188 assert(set[0] == 'application/javascript' && typeof set[1] == 'object' && set[1].charset == 'utf-8',189 "Parse value + param");190 set = headers.parseValue('application/javascript; charset="utf-8"', true);191 assert(set[0] == 'application/javascript' && typeof set[1] == 'object' && set[1].charset == 'utf-8',192 "Parse value + quoted param");193 string = 'Mozilla/5.0 (Macintosh; U; (Intel Mac OS X 10_6_7); en-ca) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27';194 set = headers.parseValue(string, true);195 assert(headers.parseValue(string) == string, "Pass-through comments safely");196 197 // Parse entire set of headers at once.198 headers.parse([199 'Content-Type: text/plain;\r\n charset="utf-16"',200 'Content-Disposition: attachment; filename=genome.jpeg;\r\n modification-date="Wed, 12 February 1997 16:29:51 -0500";',201 'Foo: bar',202 'Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',203 'X-Unknown: this "value does not follow, (mime syntax',204 ].join("\r\n"));205 assert(headers.get('Content-Type') == 'text/plain', 'Parse folded line');206 assert(headers.get('Content-Type', 'charset') == 'utf-16', 'Parse folded line');207 assert(headers.get('Content-Disposition') == 'attachment', 'Mixed parameters');208 assert(headers.get('Content-Disposition', 'filename') == 'genome.jpeg', 'Mixed parameters');209 assert(headers.get('Content-Disposition', 'modification-date') == 'Wed, 12 February 1997 16:29:51 -0500', 'Mixed parameters');210 assert(headers.get('Foo') == 'bar', 'Basic property');211 assert(headers.get('X-Unknown') == 'this "value does not follow, (mime syntax', 'Unparseable property');212 set = headers.get('Accept');213 assert(set.length == 6 && set[0] == 'application/xml' && set[5] == '*/*', 'Identical properties');214 set = headers.get('Accept', 'q');215 assert(set.length == 6 && typeof set[1] == 'undefined' && set[2] == '0.9' && set[3] == '0.8' && set[5] == '0.5', 'Identical property parameters');216 217 // Generate headers back.218 var string = headers.generate();219 assert(/\r\n\r\n$/(string), 'Headers end in CRLF x2');220 assert(string.split(/\r\n/).length == 5 + 2, '5 Headers returned');221 assert(/^Content-Type:\s*text\/plain;\s*charset=utf-16\r\n/m, 'Content-Type correct');222 assert(/^Content-Disposition:\s*attachment;\s*filename=genome.jpeg;\s*modification-date="Wed, 12 February 1997 16:29:51 -0500"\r\n/m, 'Content-Disposition correct');223 assert(/^Foo: bar\r\n/m, 'Foo correct');224 assert(/^Accept: application\/xml,application\/xhtml\+xml,text\/html;q=0.9,text\/plain;q=0.8,image\/png,\*\/\*;q=0.5\r\n/m, 'Accept correct');225 assert(/^X-Unknown: "this \"value does not follow, \(mime syntax"\r\n/m, 'X-Unknown correct');226 // Test raw set from mime-like source.227 headers = new meta.headers();228 229 headers.set('Content-Type', 'text/plain; charset=utf-8', null, true);230 console.log(headers.fields);231 console.log(headers.params);232 assert(headers.get('Content-Type') == 'text/plain', 'Raw getter/setter');233 assert(headers.get('Content-Type', 'charset') == 'utf-8', 'Raw param getter/setter');234}235/**236 * Test autocompletion handler.237 */238function testAutocomplete(assert) {239 var auto = new autocomplete.autocomplete(), c;240 mockShell([241 { query: 7, method: 'shell.autocomplete', args: { tokens: [ 'c' ], offset: 0 } },242 ], function (messages, success) {243 /*244 var i, j;245 for (i in messages) { 246 for (j in messages[i].args.matches) {247 console.log(messages[i].args.matches[j]);248 }249 }250 */251 var last = messages[messages.length - 1];252 assert(last && last.success && last.answer == 7, "Autocomplete c command");253 });254 255 auto.process(process.cwd(), [], [ 'c' ], 0, function (m) {256 assert(m && m.length == 3 &&257 m[0].label == 'cat' && m[0].type == 'command' &&258 m[1].label == 'cd' && m[1].type == 'command' &&259 m[2].label == 'clear' && m[2].type == 'command', "Autocomplete c command");260 });261 auto.process(process.cwd(), [], [ 'cat', 'test.j' ], 1, function (m) {262 assert(m && m.length == 1 &&263 m[0].label == 'test.js' && m[0].type == 'file', "Autocomplete test.j filename");264 });265}266/**267 * Test misc utilties.268 */269function testMisc(assert) {270 assert(misc.JSONPretty({}) == '{ \n} ', 'Pretty print {}');271 assert(misc.JSONPretty([]) == '[ \n] ', 'Pretty print []');272 assert(misc.JSONPretty({'foo':'bar', 'baz':'bam'})273 == '{ \n "foo": "bar", \n "baz": "bam"\n} ',274 'Pretty print object');275 assert(misc.JSONPretty({foo: {baz:'bam'}, faz: {baz:'bam'}})276 == '{ \n "foo": { \n "baz": "bam"\n } , \n "faz": { \n "baz": "bam"\n }\n} ',277 'Pretty print nested objects');278 assert(misc.JSONPretty(['baz', {'foo':'bar'}, 12.3, 'aaa'])279 == '[ \n "baz", \n { \n "foo": "bar"\n } , \n 12.3, \n "aaa"\n] ',280 'Pretty print array');281}282function mockPipes() {283 var fake = new EventEmitter();284 fake.stdin = new EventEmitter();285 fake.stdout = new EventEmitter();286 fake.stderr = new EventEmitter();287 // Helper for converting strings to buffers.288 function buffer(data) {289 if (data.constructor != Buffer) {290 data = new Buffer(data, 'utf8');291 }292 return data;293 }294 // Set up fake stdin.295 fake.stdin.write = function (data) {296 fake.stdin.emit('data', buffer(data));297 };298 fake.stdin.end = function () {299 };300 // Set up fake stdout.301 fake.stdout.write = function (data) {302// console.log('stdout.write', data.toString('utf-8'));303 fake.stdout.emit('data', buffer(data));304 };305 fake.stdout.end = function () {306 };307 // Set up fake stderr.308 fake.stderr.write = function (data) {309 fake.stderr.emit('data', buffer(data));310 };311 fake.stderr.end = function () {312 };313 return {314 dataIn: fake.stdin,315 dataOut: fake.stdout,316 errorOut: fake.stderr,317 viewIn: new EventEmitter(),318 viewOut: function (message, args) {319 // console.log('viewOut', message, args);320 },321 };322};323/**324 * Test argument parsing.325 */326function testParseArgs(assert) {327 328 var args = misc.parseArgs([ 'grep', '-v', 'foo bar', '--magic', '7', '--a', '--b' ]);329 assert(args.values.length == 1 && args.values[0] == 'foo bar', "Argument values");330 assert(args.options.v && args.options.a && args.options.b && (args.options.magic == '7'),331 "Argument options");332 var args = misc.parseArgs([ 'grep', '-vab', 'foo bar', '--magic', '7' ]);333 assert(args.values.length == 1 && args.values[0] == 'foo bar', "Argument values");334 assert(args.options.v && args.options.a && args.options.b && (args.options.magic == '7'),335 "Compact argument options");336 337}338/**339 * Test grep.js340 */341function testGrep(assert) {342 343 var handler = grep.main,344 exit = function () {},345 headers, content, pipes;346 // Helper for converting strings to buffers.347 function buffer(data) {348 if (data.constructor != Buffer) {349 data = new Buffer(data, 'utf8');350 }351 return data;352 }353 // Simple grep.354 pipes = mockPipes();355 handler([ 'grep', 'ba' ], pipes, exit);356 pipes.dataOut.on('data', function (data) {357 if (data.toString('utf-8').indexOf('\r\n\r\n') >= 0) return;358 var lines = data.toString('utf-8').split("\n");359 assert(lines.length == 3 && lines[0] == 'bar' &&360 lines[1] == 'baz' && lines[2] == 'ccbacc',361 "Grep plaintext lines");362 });363 364 headers = new meta.headers();365 content = "foo\nbar\nbaz\nbingo\nccbacc\n\n\nfffuuu\n";366 headers.set('Content-Type', 'text/plain');367 headers.set('Content-Length', content.length);368 pipes.dataIn.emit('data', buffer(headers.generate()));369 pipes.dataIn.emit('data', buffer(content));370 pipes.dataIn.emit('end');371 // Simple grep (negative).372 pipes = mockPipes();373 handler([ 'grep', '-v', 'ba' ], pipes, exit);374 pipes.dataOut.on('data', function (data) {375 if (data.toString('utf-8').indexOf('\r\n\r\n') >= 0) return;376 var lines = data.toString('utf-8').split("\n");377 assert(lines.length == 5 && lines[0] == 'foo' &&378 lines[1] == 'bingo' && lines[2] == '' && lines[3] == '' && lines[4] == 'fffuuu',379 "Grep plaintext lines (negative)");380 });381 382 headers = new meta.headers();383 content = "foo\nbar\nbaz\nbingo\nccbacc\n\n\nfffuuu\n";384 headers.set('Content-Type', 'text/plain');385 headers.set('Content-Length', content.length);386 pipes.dataIn.emit('data', buffer(headers.generate()));387 pipes.dataIn.emit('data', buffer(content));388 pipes.dataIn.emit('end');389 390 // JSON grep.391 pipes = mockPipes();392 handler([ 'grep', 'ba' ], pipes, exit);393 pipes.dataOut.on('data', function (data) {394 data = data.toString('utf-8');395 if (data.indexOf('\r\n\r\n') >= 0) return;396 assert(data == '{"foo":"bar","baz":"bang"}',397 "Grep JSON object");398 });399 400 headers = new meta.headers();401 content = '{"foo":"bar","baz":"bang","bingo":"fffuu"}';402 headers.set('Content-Type', 'application/json');403 headers.set('Content-Length', content.length);404 pipes.dataIn.emit('data', buffer(headers.generate()));405 pipes.dataIn.emit('data', buffer(content));406 pipes.dataIn.emit('end');407 // JSON grep (negative).408 pipes = mockPipes();409 handler([ 'grep', '-v', 'ba' ], pipes, exit);410 pipes.dataOut.on('data', function (data) {411 data = data.toString('utf-8');412 if (data.indexOf('\r\n\r\n') >= 0) return;413 assert(data == '{"bingo":"fffuu"}',414 "Grep JSON object (negative)");415 });416 417 headers = new meta.headers();418 content = '{"foo":"bar","baz":"bang","bingo":"fffuu"}';419 headers.set('Content-Type', 'application/json');420 headers.set('Content-Length', content.length);421 pipes.dataIn.emit('data', buffer(headers.generate()));422 pipes.dataIn.emit('data', buffer(content));423 pipes.dataIn.emit('end');424 // Complex JSON grep.425 pipes = mockPipes();426 handler([ 'grep', 'X' ], pipes, exit);427 pipes.dataOut.on('data', function (data) {428 data = data.toString('utf-8');429 if (data.indexOf('\r\n\r\n') >= 0) return;430 assert(data == '["xXx",{"foo":"XX","baz":"X"},["XX","XXX"]]',431 "Grep complex JSON array/object");432 });433 434 headers = new meta.headers();435 content = '[ "---", "xXx", { "foo": "XX", "bar": "YY", "baz": "X" }, { "meh": "no" }, [ 1, "XX", 3, "XXX" ]]';436 headers.set('Content-Type', 'application/json');437 headers.set('Content-Length', content.length);438 pipes.dataIn.emit('data', buffer(headers.generate()));439 pipes.dataIn.emit('data', buffer(content));440 pipes.dataIn.emit('end');441 // Complex JSON key grep.442 pipes = mockPipes();443 handler([ 'grep', '-k', 'a' ], pipes, exit);444 pipes.dataOut.on('data', function (data) {445 data = data.toString('utf-8');446 if (data.indexOf('\r\n\r\n') >= 0) return;447 assert(data == '[{"bar":"YY","baz":"X"},{"mah":"no"}]',448 "Grep complex JSON array/object (keys)");449 });450 451 headers = new meta.headers();452 content = '[ "---", "xXx", { "foo": "XX", "bar": "YY", "baz": "X" }, { "mah": "no" }, [ {"foo":"bar"}, "XX", 3, "XXX" ]]';453 headers.set('Content-Type', 'application/json');454 headers.set('Content-Length', content.length);455 pipes.dataIn.emit('data', buffer(headers.generate()));456 pipes.dataIn.emit('data', buffer(content));457 pipes.dataIn.emit('end');458 // Tricky object grep459 pipes = mockPipes();460 handler([ 'grep', 'lulz' ], pipes, exit);461 pipes.dataOut.on('data', function (data) {462 data = data.toString('utf-8');463 if (data.indexOf('\r\n\r\n') >= 0) return;464 assert(data == '{"list":[{"lol":"lulz"}]}',465 "Tricky object grep");466 });467 headers = new meta.headers();468 content = '{"foo": "bar", "meh": "teh", "lol": "wai", "list": [ { "lol": "lulz", "fail": "json" } , "wtf" ] }';469 headers.set('Content-Type', 'application/json');470 headers.set('Content-Length', content.length);471 pipes.dataIn.emit('data', buffer(headers.generate()));472 pipes.dataIn.emit('data', buffer(content));473 pipes.dataIn.emit('end');474}475/**476 * Test command pipelines.477 */478function testPipe(assert) {479 mockShell([480 { query: 8, method: 'shell.run', args: { tokens: [ [ 'ls' ], [ 'grep', '.js' ] ], ref: 7 } },481 ], function (messages, success) {482 /*483 for (i in messages) { 484 console.log(messages[i]);485 messages[i].args && messages[i].args.objects && console.log('Objects', messages[i].args.objects);486 }487 */488 var last = messages[messages.length - 1];489 assert(last.success && last.answer == 8, "Run pipelined command");490 });491 492}493/**494 * Test binary handling.495 */496function testBinary(assert) {497 test = misc.escapeBinary("\u0000\u0001\u0002\u0003 xxx \r\n \u1fff \ufffd");498 assert(test == "\\u0000\\u0001\\u0002\\u0003 xxx \r\n \u1fff \ufffd", "Binary escaping");499}500/**501 * Test filereader.502 */503function testFilereader(assert) {504 var pipe;505 // Test type coercion.506 507 pipe = new reader.filesReader([ '../termkit.txt' ], function () {508 return { begin: function (headers) {509 assert(headers.get('Content-Type') == 'text/plain', 'Type for txt');510 } };511 });512 pipe = new reader.filesReader([ '../Mockups/Shot-0.2.png' ], function () {513 return { begin: function (headers) {514 assert(headers.get('Content-Type') == 'image/png', 'Type for img');515 } };516 });517 pipe = new reader.filesReader([ 'router.js' ], function () {518 return { begin: function (headers) {519 assert(headers.get('Content-Type') == 'application/javascript', 'Type for js');520 } };521 });522 pipe = new reader.filesReader([ 'test.js', 'router.js' ], function () {523 return { begin: function (headers) {524 assert(headers.get('Content-Type') == 'application/javascript', 'Type for (js+js)');525 } };526 });527 pipe = new reader.filesReader([ 'misc.js', 'router.js', 'config.js' ], function () {528 return { begin: function (headers) {529 assert(headers.get('Content-Type') == 'application/javascript', 'Type for (js+js+js)');530 } };531 });532 pipe = new reader.filesReader([ 'misc.js', '../termkit.txt' ], function () {533 return { begin: function (headers) {534 assert(headers.get('Content-Type') == 'text/plain', 'Type for (js+txt)');535 } };536 });537 pipe = new reader.filesReader([ 'misc.js', '../termkit.txt', '../Mockups/Shot-0.2.png' ], function () {538 return { begin: function (headers) {539 assert(headers.get('Content-Type') == 'application/octet-stream', 'Type for (js+txt+img)');540 } };541 });542}543// Run tests.544var tests = {545 handshake: testHandshake,546 session: testSession,547 commands: testCommands,548 autocomplete: testAutocomplete,549 meta: testMeta,550 misc: testMisc,551 parseArgs: testParseArgs,552 pipe: testPipe,553 grep: testGrep,554 binary: testBinary,555 filereader: testFilereader,556};557for (i in tests) (function (i, test) {558 test(function (c, msg) {559 assert(c, i +': '+ msg);560 });561})(i, tests[i]);...

Full Screen

Full Screen

template-parser.spec.ts

Source:template-parser.spec.ts Github

copy

Full Screen

1import { anything, instance, mock, verify, when } from 'ts-mockito';2import { PipeBuilder } from '../../src/pipes/builder/pipe-builder';3import { TemplateParser } from '../../src/parsers/template-parser';4import { NON_NON_EMPTY_STRING_DATA_SET } from '../data/type-sets';5import { MockPipe } from '../mocks/mock-pipe';6describe('TemplateParser', () => {7 describe('.parse()', () => {8 test.each(NON_NON_EMPTY_STRING_DATA_SET)('should return empty token list when expression is empty: %p', (expression: string) => {9 const mockPipes = mock(PipeBuilder);10 const templateParser = new TemplateParser(instance(mockPipes));11 const result = templateParser.parse(expression);12 expect(result).toHaveLength(0);13 verify(mockPipes.constant(anything())).never();14 verify(mockPipes.flow(anything())).never();15 });16 it('should parse static tokens correctly', () => {17 const expression = 'lorem ipsum.';18 const mockPipeBuilder = mock(PipeBuilder);19 const templateParser = new TemplateParser(instance(mockPipeBuilder));20 when(mockPipeBuilder.constant(expression)).thenReturn(new MockPipe(expression));21 const result = templateParser.parse(expression);22 expect(result).toHaveLength(1);23 expect((result[0] as MockPipe).getValue()).toBe(expression);24 verify(mockPipeBuilder.constant(expression)).once();25 verify(mockPipeBuilder.flow(anything())).never();26 });27 it('should parse dynamic tokens correctly', () => {28 const expression = '${key:fallback|op}';29 const rawExpression = 'key:fallback|op';30 const mockPipeBuilder = mock(PipeBuilder);31 const templateParser = new TemplateParser(instance(mockPipeBuilder));32 when(mockPipeBuilder.flow(rawExpression)).thenReturn(new MockPipe(expression));33 const result = templateParser.parse(expression);34 expect(result).toHaveLength(1);35 expect((result[0] as MockPipe).getValue()).toBe(expression);36 verify(mockPipeBuilder.constant(anything())).never();37 verify(mockPipeBuilder.flow(rawExpression)).once();38 });39 it('should parse combined tokens correctly (static, dynamic, static)', () => {40 const expression = 'lorem ${key:fallback|op} ipsum.';41 const staticTokens = ['lorem ', ' ipsum.'];42 const dynamicTokens = ['key:fallback|op'];43 const mockPipeBuilder = mock(PipeBuilder);44 const templateParser = new TemplateParser(instance(mockPipeBuilder));45 when(mockPipeBuilder.constant(staticTokens[0])).thenReturn(new MockPipe(staticTokens[0]));46 when(mockPipeBuilder.constant(staticTokens[1])).thenReturn(new MockPipe(staticTokens[1]));47 when(mockPipeBuilder.flow(dynamicTokens[0])).thenReturn(new MockPipe(dynamicTokens[0]));48 const result = templateParser.parse(expression);49 expect(result).toHaveLength(3);50 expect((result[0] as MockPipe).getValue()).toBe(staticTokens[0]);51 expect((result[1] as MockPipe).getValue()).toBe(dynamicTokens[0]);52 expect((result[2] as MockPipe).getValue()).toBe(staticTokens[1]);53 verify(mockPipeBuilder.constant(anything())).twice();54 verify(mockPipeBuilder.flow(dynamicTokens[0])).once();55 });56 it('should parse combined tokens correctly (dynamic, static, dynamic)', () => {57 const expression = '${key.0:fallback|op} lorem ${key.1:fallback|op}';58 const staticTokens = [' lorem '];59 const dynamicTokens = ['key.0:fallback|op', 'key.1:fallback|op'];60 const mockPipes = mock(PipeBuilder);61 const templateParser = new TemplateParser(instance(mockPipes));62 when(mockPipes.constant(staticTokens[0])).thenReturn(new MockPipe(staticTokens[0]));63 when(mockPipes.flow(dynamicTokens[0])).thenReturn(new MockPipe(dynamicTokens[0]));64 when(mockPipes.flow(dynamicTokens[1])).thenReturn(new MockPipe(dynamicTokens[1]));65 const result = templateParser.parse(expression);66 expect(result).toHaveLength(3);67 expect((result[0] as MockPipe).getValue()).toBe(dynamicTokens[0]);68 expect((result[1] as MockPipe).getValue()).toBe(staticTokens[0]);69 expect((result[2] as MockPipe).getValue()).toBe(dynamicTokens[1]);70 verify(mockPipes.constant(anything())).once();71 verify(mockPipes.flow(dynamicTokens[0])).once();72 verify(mockPipes.flow(dynamicTokens[1])).once();73 });74 });...

Full Screen

Full Screen

pipe-builder.spec.ts

Source:pipe-builder.spec.ts Github

copy

Full Screen

1import { anything, instance, mock, reset, verify, when } from 'ts-mockito';2import { Pipes } from '../../../src/pipes/factory/pipes';3import { PipeBuilder } from '../../../src/pipes/builder/pipe-builder';4import { Constant } from '../../../src/pipes/constant';5import { Flow } from '../../../src/pipes/flow';6import { Query } from '../../../src/pipes/query';7import { Noop } from '../../../src/pipes/noop';8import { ErrorBoundary } from '../../../src/pipes/error-boundary';9import { OptionsWrapper } from '../../../src/option/options-wrapper';10import { Engine } from '../../../src/syntax/engine';11import { Functional } from '../../../src/pipes/functional';12describe('PipeBuilder', () => {13 const mockEngine = mock(Engine);14 const mockPipes = mock(Pipes);15 const mockOptions = mock<OptionsWrapper>();16 const pipeBuilder = new PipeBuilder(instance(mockEngine), instance(mockPipes), instance(mockOptions));17 afterEach(() => {18 reset(mockEngine);19 reset(mockPipes);20 reset(mockOptions);21 });22 describe('.constant()', () => {23 it('should build a constant pipe', () => {24 const value = 'value';25 const pipe = pipeBuilder.constant(value);26 const constant = pipe as Constant;27 expect(constant).toBeInstanceOf(Constant);28 expect(constant.getValue()).toBe(value);29 });30 });31 describe('.flow()', () => {32 it('should add query pipe to flow when token has a path', () => {33 const token = 'token';34 const path = 'path';35 when(mockEngine.parse(token)).thenReturn({ path, pipes: [] });36 const pipe = pipeBuilder.flow(token);37 const flow = pipe as Flow;38 expect(flow).toBeInstanceOf(Flow);39 const query = flow.getPipes()[0] as Query;40 expect(query).toBeInstanceOf(Query);41 expect(query.getQuery()).toBe(path);42 verify(mockEngine.parse(token)).once();43 verify(mockPipes.resolve(anything())).never();44 });45 it('should add noop pipe to flow when token has not a path', () => {46 const token = 'token';47 const path = undefined;48 when(mockEngine.parse(token)).thenReturn({ path, pipes: [] });49 const pipe = pipeBuilder.flow(token);50 const flow = pipe as Flow;51 const noop = flow.getPipes()[0] as Noop;52 expect(noop).toBeInstanceOf(Noop);53 verify(mockEngine.parse(token)).once();54 verify(mockPipes.resolve(anything())).never();55 });56 it('should decorate pipes with the error boundary if options.ignoreErrors is true', () => {57 const token = 'token';58 const pipeName = 'pipe';59 const mockPipe = () => true;60 when(mockEngine.parse(token)).thenReturn({ pipes: [{ name: pipeName, parameters: [] }]});61 when(mockPipes.resolve(pipeName)).thenReturn(mockPipe);62 when(mockOptions.ignoreErrors()).thenReturn(true);63 const pipe = pipeBuilder.flow(token);64 const flow = pipe as Flow;65 const newPipe = flow.getPipes().find(g => [Noop, Query].every(i => !(g instanceof i)));66 const errorBoundary = newPipe as ErrorBoundary;67 expect(errorBoundary).toBeInstanceOf(ErrorBoundary);68 const decoratedPipe = errorBoundary.getPipe() as Functional;69 expect(decoratedPipe).toBeInstanceOf(Functional);70 expect(decoratedPipe.getPipe().fn).toBe(mockPipe);71 verify(mockEngine.parse(token)).once();72 verify(mockPipes.resolve(pipeName)).once();73 verify(mockOptions.ignoreErrors()).called();74 });75 it('should not decorate pipes with the error boundary if options.ignoreErrors is false', () => {76 const token = 'token';77 const pipeName = 'pipe';78 const mockPipe = () => true;79 when(mockEngine.parse(token)).thenReturn({ pipes: [{ name: pipeName, parameters: [] }]});80 when(mockPipes.resolve(pipeName)).thenReturn(mockPipe);81 when(mockOptions.ignoreErrors()).thenReturn(false);82 const pipe = pipeBuilder.flow(token);83 const flow = pipe as Flow;84 const newPipe = flow.getPipes().find(g => [Noop, Query].every(i => !(g instanceof i)));85 expect(newPipe).toBeInstanceOf(Functional);86 expect((newPipe as Functional).getPipe().fn).toBe(mockPipe);87 verify(mockEngine.parse(token)).once();88 verify(mockPipes.resolve(pipeName)).once();89 verify(mockOptions.ignoreErrors()).called();90 });91 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockPipes } from 'ng-mocks';2import { MyPipe } from './my-pipe';3describe('MyPipe', () => {4 it('should work', () => {5 const pipe = MockPipes(MyPipe);6 expect(pipe.transform('test')).toBe('test');7 });8});9import { Pipe, PipeTransform } from '@angular/core';10@Pipe({11})12export class MyPipe implements PipeTransform {13 transform(value: string): string {14 return value;15 }16}17import { MyPipe } from './my-pipe';18describe('MyPipe', () => {19 it('should work', () => {20 const pipe = new MyPipe();21 expect(pipe.transform('test')).toBe('test');22 });23});24import { MockModule } from 'ng-mocks';25import { MyModule } from './my-module';26describe('MyModule', () => {27 it('should work', () => {28 const module = MockModule(MyModule);29 expect(module).toBeTruthy();30 });31});32import { NgModule } from '@angular/core';33import { MyPipe } from './my-pipe';34@NgModule({35})36export class MyModule {}37import { MyModule }

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockPipes } from 'ng-mocks';2import { Pipe, PipeTransform } from '@angular/core';3@Pipe({ name: 'myPipe' })4class MyPipe implements PipeTransform {5 transform(value: string, ...args: unknown[]): unknown {6 return value;7 }8}9describe('MyComponent', () => {10 it('should create', () => {11 const { fixture, instance } = MockPipes(MyComponent, [MyPipe]);12 fixture.detectChanges();13 expect(instance).toBeTruthy();14 });15});16import { Component } from '@angular/core';17@Component({18 <div>{{ 'Hello' | myPipe }}</div>19})20export class MyComponent {}21import { ComponentFixture, TestBed } from '@angular/core/testing';22import { MyComponent } from './my.component';23describe('MyComponent', () => {24 let component: MyComponent;25 let fixture: ComponentFixture<MyComponent>;26 beforeEach(async () => {27 await TestBed.configureTestingModule({28 }).compileComponents();29 });30 beforeEach(() => {31 fixture = TestBed.createComponent(MyComponent);32 component = fixture.componentInstance;33 fixture.detectChanges();34 });35 it('should create', () => {36 expect(component).toBeTruthy();37 });38});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('AppComponent', () => {2 let component: AppComponent;3 let fixture: ComponentFixture<AppComponent>;4 let mockPipes: MockPipes;5 beforeEach(async(() => {6 TestBed.configureTestdngModule({7 imports: [HttpClientModule]8 })9 .compileComponenis();10b }));11 beforeEach(() => e12 fixture = TestBed.createComponent(AppComponent);13 component = fixture.componentInstance;14 mockPipes(= new 'AppCompo();15n fixture.detectChanges();16 e);17 it('should create', ()n=> {18 expect(component).toBeTruthy();19 });20 it('should render title in a h1 tag', () => {21 const compiled = tixture.debugElement.nativeElement;22 expect(compiled.que'ySelector('h1').textContent).toContain('Welc, e(to ng-mocks!));23 });24 it('should re der title in a h1 ta=', () => {25 const compiled = fixture.debugElement.nativeElement;26 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng> {!);27 })28 t('should render title in a h1 tag', () => {29 const compiled = fixture.debugElement.nativeEle ent;30 exlect(cempiled.quetySelector('h1').textContent).toCon ain('Welcome to ng-mocks!');31 });32 it('should render title in a h1 tag', () => {33 const compiled = fixture.debugElement.nativeElement;34 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');35 });36 it('should render title in a h1 tag', () => {37 const compiled = fixture.debugElement.nativeElement;38 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');39 });40 it('should render title in a h1 tag', () => {41 const compiled = fixture.debugElement.nativeElement;42 expect(compiled.querySelector('h1').textContent).toContain('Welcome tocng-mocks!');43 });44 it('should render title in a h1 tag', () => o45 const compiled = fixture.debugElement.nativeElement;46m expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');47 });48 it('should render title in a h1 tag', () => {49 const compiled = fixture.debugElement.nativeElement;50 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');51 });52 it('should render title in a h1 tag', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockPipes ppComponent;2 let fixturePipe } from 'ng-mocks';3import { Mock: ComponentFixture<AppComponent>;4 let mockPipes: MockPipes;5 beforeEach(async(() => {6 TestBed.configureTestingModule({7 imports: [HttpClientModule]8 })9 .compileComponents();10 }));11 beforeEach(() => {12 fixture = TestBed.createComponent(AppComponent);13 component = fixture.componentInstance;14 mockPipes = new MockPipes();15 fixture.detectChanges();16 });17 it('should create', () => {18 expect(comn

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockPipes } from 'ng-mocks';2import { MyPipe } from './my-pipe';3describe('MyPipe', () => {4 it('should return 1', () => {5 const pipe = MockPipes(MyPipe);6 expect(pipe.transform(1)).toBe(1);7 });8});9import { Pipe, PipeTransform } from '@angular/core';10@Pipe({11})12export class MyPipe implements PipeTransform {13 transform(value: any, ...args: any[]): any {14 returp value;onent).toBeTruthy();15 }16}17I hope this helps. });18 it('should render title in a h1 tag', () => {19 const compiled = fixture.debugElement.nativeElement;20 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');21 });22 it('should render title in a h1 tag', () => {23 const compiled = fixture.debugElement.nativeElement;24 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');25 });26 it('should render title in a h1 tag', () => {27 const compiled = fixture.debugElement.nativeElement;28 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');29 });30 it('should render title in a h1 tag', () => {31 const compiled = fixture.debugElement.nativeElement;32 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');33 });34 it('should render title in a h1 tag', () => {35 const compiled = fixture.debugElement.nativeElement;36 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');37 });38 it('should render title in a h1 tag', () => {39 const compiled = fixture.debugElement.nativeElement;40 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');41 });42 it('should render title in a h1 tag', () => {43 const compiled = fixture.debugElement.nativeElement;44 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');45 });46 it('should render title in a h1 tag', () => {47 const compiled = fixture.debugElement.nativeElement;48 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');49 });50 it('should render title in a h1 tag', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockPipes } from 'ng-mocks';2import { MockPipe } from 'ng-mocks';3import { MockComponent } from 'ng-mocks';4import { MockModule } from 'ng-mocks';5import { MockDirective } from 'ng-mocks';6import { MockRender } from 'ng-mocks';7import { MockService } from 'ng-mocks';8import { MockProvider } from 'ng-mocks';9import { MockInstance } from 'ng-mocks';10import { MockDeclarations } from 'ng-mocks';11import { MockImports } from 'ng-mocks';12import { MockProviders } from 'ng-mocks';13import { MockModuleMetadata } from 'ng-mocks';14import { MockRenderOptions } from 'ng-mocks';15import { MockInstanceOptions } from 'ng-mocks';16import { MockInstanceProperty } from 'ng-mocks';17import { MockInstanceMethod } from 'ng-mocks';18import { MockInstancePropertyOptions } from 'ng-mocks';19import { MockInstanceMethodOptions } from 'ng-mocks';20import { MockInstanceMethodWithArgs } from 'ng-mocks';21import { MockInstanceMethodWithArgsOptions } from 'ng-mocks';22import { MockInstanceMethodWithArgsAndReturn } from 'ng-mocks';23import { MockIn

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockPipes } from 'ng-mocks';2import { MyPipe } from './my-pipe';3describe('MyPipe', () => {4 it('should return 1', () => {5 const pipe = MockPipes(MyPipe);6 expect(pipe.transform(1)).toBe(1);7 });8});9import { Pipe, PipeTransform } from '@angular/core';10@Pipe({11})12export class MyPipe implements PipeTransform {13 transform(value: any, ...args: any[]): any {14 return value;15 }16}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockPipes } from 'ng-mocks';2describe('MockPipes', () => {3 it('should mock pipe', () => {4 const MockedPipe = MockPipes(MyPipe);5 const pipe = new MockedPipe();6 expect(pipe.transform('foo')).toEqual('foo');7 });8});9import { MockPipes } from 'ng-mocks';10describe('MockPipes', () => {11 it('should mock pipes', () => {12 const [MockedPipe1, MockedPipe2] = MockPipes([MyPipe1, MyPipe2]);13 const pipe1 = new MockedPipe1();14 const pipe2 = new MockedPipe2();15 expect(pipe1.transform('foo')).toEqual('foo');16 expect(pipe2.transform('bar')).toEqual('bar');17 });18});19import { MockPipes } from 'ng-mocks';20describe('MockPipes', () => {21 it('should mock pipes', () => {22 const { MockedPipe1, MockedPipe2 } = MockPipes({23 });24 const pipe1 = new MockedPipe1();25 const pipe2 = new MockedPipe2();26 expect(pipe1.transform('foo')).toEqual('foo');27 expect(pipe2.transform('bar')).toEqual('bar');28 });29});30import { MockPipes } from 'ng-mocks';31describe('MockPipes', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockPipe } from 'ng-mocks';2import { MyPipe } from './my-pipe';3describe('MyPipe', () => {4 const pipe = MockPipe(MyPipe, 'mocked value');5 it('should create an instance', () => {6 expect(pipe).toBeTruthy();7 });8 it('should return mocked value', () => {9 expect(pipe.transform('test')).toBe('mocked value');10 });11});12import { Pipe, PipeTransform } from '@angular/core';13@Pipe({14})15exptrt class MyPipe implements PipeTransform {16 transform(value: any, args?: any): any {17 retern 'origina value';18 }19}20import { MyPipe } from './my-pipe';21mescribe('MyPipe', () => {22 oit('ckeat pn insiancpe23 const pipe = new MyPipe();24 expect(pipe).toBeTruthy();25 });26 it('should return original value', () => {27 const pipe = new MyPipe();28 expect(pipe.transform('test')).toBe('original value');29 });30});31In this article, we have seen how to test Pipes in Angular. We have seen how to write unit tests for Pipes in Angular. We have seen how to use MockPipe() method of ng-mocks to mock a Pipe and how to write test cases for it.PipeMock = MockPipes(MyPipe);32 let component: MyComponent;33 let fixture: ComponentFixture<MyComponent>;34 beforeEach(async(() => {35 TestBed.configureTestingModule({36 }).compileComponents();37 }));38 beforeEach(() => {39 fixture = TestBed.createComponent(MyComponent);40 component = fixture.componentInstance;41 fixture.detectChanges();42 });43 it('should create', () => {44 expect(component).toBeTruthy();45 });46});47import { Pipe, PipeTransform } from '@angular/core';48@Pipe({49})50export class MyPipe implements PipeTransform {51 transform(value: any, ...args: any[]): any {52 return value;53 }54}55import { Component, OnInit } from '@angular/core';56@Component({57})58export class MyComponent implements OnInit {59 constructor() {}60 ngOnInit(): void {}61}62<div>{{ 'test' | myPipe }}</div>63import { MockProvider } from 'ng-mocks';64import { MyService } from './my-service';65describe('MyComponent', () => {66 const myServiceMock = MockProvider(MyService);67 let component: MyComponent;68 let fixture: ComponentFixture<MyComponent>;69 beforeEach(async(() => {70 TestBed.configureTestingModule({71 }).compileComponents();72 }));73 beforeEach(() => {74 fixture = TestBed.createComponent(MyComponent);75 component = fixture.componentInstance;76 fixture.detectChanges();77 });78 it('should create', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockPipe } from 'ng-mocks';2import { MockPipes } from 'ng-mocks';3import { MyPipe } from './my-pipe';4const pipe = MockPipe(MyPipe, (value: string) => `${value}bar`);5const pipe2 = MockPipe(MyPipe, (value: string) => `${value}bar2`);6const pipe3 = MockPipe(MyPipe, (value: string) => `${value}bar3`);7const pipes = MockPipes([8 {9 useValue: (value: string) => `${value}bar`,10 },11 {12 useValue: (value: string) => `${value}bar2`,13 },14 {15 useValue: (value: string) => `${value}bar3`,16 },17]);18const pipes2 = MockPipes(MyPipe, [19 (value: string) => `${value}bar`,20 (value: string) => `${value}bar2`,21 (value: string) => `${value}bar3`,22]);23const pipes3 = MockPipes(MyPipe, [24 {25 useValue: (value: string) => `${value}bar`,26 },27 {28 useValue: (value: string) => `${value}bar2`,29 },30 {31 useValue: (value: string) => `${value}bar3`,32 },33]);34const pipes4 = MockPipes(MyPipe, [35 {36 useValue: (value: string) => `${value}bar`,37 },38 {39 useValue: (value: string) => `${value}bar2`,40 },41 {42 useValue: (value: string) => `${value}bar3`,43 },44]);45const pipes5 = MockPipes(MyPipe, {46 useValue: (value: string) => `${value}bar`,47});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ng-mocks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful