How to use type.slice method in Cypress

Best JavaScript code snippet using cypress

fragments.js

Source:fragments.js Github

copy

Full Screen

1/*eslint-env node, mocha */2var Prismic = require('../lib/prismic.js');3var chai = require('chai');4var assert = chai.assert,5 microRepository = 'https://micro.prismic.io/api',6 previewToken = 'MC5VcXBHWHdFQUFONDZrbWp4.77-9cDx6C3lgJu-_vXZafO-_vXPvv73vv73vv70777-9Ju-_ve-_vSLvv73vv73vv73vv70O77-977-9Me-_vQ';7function getLinkResolver(ref) {8 return function(doc, isBroken) {9 if (isBroken) return '#broken';10 return "/testing_url/" + doc.id + "/" + doc.slug + (ref ? ('?ref=' + ref) : '');11 };12}13describe('Document manipulation', function() {14 it('Render a document to Html', function () {15 return Prismic.api(microRepository).then(function (Api) {16 return Api.form('everything').ref(Api.master()).submit().then(function (documents) {17 var first = documents.results[0];18 assert.isNotNull(first);19 first.asHtml(getLinkResolver());20 });21 });22 });23});24describe('Multiple fragment level global test', function() {25 it('getFirstImage in slice zone works', function (done) {26 var doc = Prismic.parseDoc({27 "id":"VQ_hV31Za5EAy02H",28 "uid":null,29 "type":"article",30 "href":"http://toto.wroom.dev/api/documents/search?ref=VQ_uWX1Za0oCy46m&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22VQ_hV31Za5EAy02H%22%29+%5D%5D",31 "tags":[],32 "slugs":["une-activite"],33 "linked_documents":[],34 "data":{35 "article":{36 "activities":{37 "type":"Group",38 "value":[{39 "title":{40 "type":"StructuredText",41 "value":[{42 "type":"paragraph",43 "text":"Une activité",44 "spans":[]45 }]46 },47 "image":{48 "type":"Image",49 "value":{50 "main":{51 "url":"https://wroomdev.s3.amazonaws.com/toto/ce3f52b933c4934a13422e09ed0ff6ad03a29621_hsf_evilsquall.jpg",52 "alt":"",53 "copyright":"",54 "dimensions":{"width":860,"height":640}55 },56 "views":{57 "headline":{58 "url":"https://wroomdev.s3.amazonaws.com/toto/5445d2dcd2b0c541b0406ca867ab3d07b309c944_hsf_evilsquall.jpg",59 "alt":"",60 "copyright":"",61 "dimensions":{"width":570,"height":400}62 }63 }64 }65 },66 "body":{67 "type":"StructuredText",68 "value":[{69 "type":"paragraph",70 "text":"elle est bien",71 "spans":[]72 }]73 }74 }]75 },76 "un_champ_texte":{77 "type":"Text",78 "value":"stuffgg"79 },80 "blocks":{81 "type":"SliceZone",82 "value":[{83 "type":"Slice",84 "slice_type": "features",85 "value":{86 "type":"Group",87 "value":[{88 "illustration":{89 "type":"Image",90 "value":{91 "main":{92 "url":"https://wroomdev.s3.amazonaws.com/toto/db3775edb44f9818c54baa72bbfc8d3d6394b6ef_hsf_evilsquall_first_in_slice.jpg",93 "alt":"",94 "copyright":"",95 "dimensions":{"width":4285,"height":709}96 },97 "views":{}98 }99 },100 "title":{101 "type":"Text",102 "value":"c'est un bloc features"103 }104 }]105 }106 },{107 "type":"Slice",108 "slice_type":"text",109 "value":{110 "type":"StructuredText",111 "value":[{112 "type":"paragraph",113 "text":"C'est un bloc content",114 "spans":[]115 }]116 }117 }]118 }119 }120 }121 });122 var sliceSingleElem = Prismic.parseDoc({123 "id":"VQ_hV31Za5EAy02H",124 "uid":null,125 "type":"article",126 "href":"http://toto.wroom.dev/api/documents/search?ref=VQ_uWX1Za0oCy46m&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22VQ_hV31Za5EAy02H%22%29+%5D%5D",127 "tags":[],128 "slugs":["une-activite"],129 "linked_documents":[],130 "data":{131 "article":{132 "blocks":{133 "type":"SliceZone",134 "value":[{135 "type":"Slice",136 "slice_type": "features",137 "value": {138 "type":"Image",139 "value":{140 "main":{141 "url":"https://wroomdev.s3.amazonaws.com/toto/db3775edb44f9818c54baa72bbfc8d3d6394b6ef_hsf_evilsquall_slice_single.jpg",142 "alt":"",143 "copyright":"",144 "dimensions":{"width":4285,"height":709}145 },146 "views":{}147 }148 }149 }]150 }151 }152 }153 });154 // Testing get First Image on doc level.155 assert.equal(doc.getFirstImage().getView('main').url, "https://wroomdev.s3.amazonaws.com/toto/ce3f52b933c4934a13422e09ed0ff6ad03a29621_hsf_evilsquall.jpg");156 // Testing get First Image on slice level.157 var slices = doc.getSliceZone('article.blocks');158 assert.equal(slices.getFirstImage().getView('main').url, "https://wroomdev.s3.amazonaws.com/toto/db3775edb44f9818c54baa72bbfc8d3d6394b6ef_hsf_evilsquall_first_in_slice.jpg");159 var slicesWithSingleElem = sliceSingleElem.getSliceZone('article.blocks');160 assert.equal(slicesWithSingleElem.getFirstImage().getView('main').url, "https://wroomdev.s3.amazonaws.com/toto/db3775edb44f9818c54baa72bbfc8d3d6394b6ef_hsf_evilsquall_slice_single.jpg");161 done();162 });163 it('getFirstTitle in slice zone works', function (done) {164 var doc = Prismic.parseDoc({165 "id":"VQ_hV31Za5EAy02H",166 "uid":null,167 "type":"article",168 "href":"http://toto.wroom.dev/api/documents/search?ref=VQ_uWX1Za0oCy46m&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22VQ_hV31Za5EAy02H%22%29+%5D%5D",169 "tags":[],170 "slugs":["une-activite"],171 "linked_documents":[],172 "data":{173 "article":{174 "blocks":{175 "type":"SliceZone",176 "value":[{177 "type":"Slice",178 "slice_type": "features",179 "value":{180 "type":"Group",181 "value":[{182 "illustration":{183 "type":"Image",184 "value":{185 "main":{186 "url":"https://wroomdev.s3.amazonaws.com/toto/db3775edb44f9818c54baa72bbfc8d3d6394b6ef_hsf_evilsquall_first_in_slice.jpg",187 "alt":"",188 "copyright":"",189 "dimensions":{"width":4285,"height":709}190 },191 "views":{}192 }193 },194 "title":{195 "type":"Text",196 "value":"c'est un bloc features"197 }198 }]199 }200 },{201 "type":"Slice",202 "slice_type":"text",203 "value":{204 "type":"StructuredText",205 "value":[{206 type: "heading2",207 text: "As seen by fine pastry as a field",208 spans: []209 }, {210 "type":"paragraph",211 "text":"C'est un bloc content",212 "spans":[]213 }]214 }215 }, {216 "type": "Slice",217 "slice_type": "ma-nouvelle-slice",218 "slice_label": null,219 "repeat": [220 {221 "text": {222 "type": "StructuredText",223 "value": [224 {225 "type": "paragraph",226 "text": "some text",227 spans: []228 }229 ]230 }231 }232 ],233 "non-repeat": {234 "text": {235 "type": "StructuredText",236 "value": [237 {238 "type": "heading2",239 "text": "some other text",240 spans: []241 }242 ]243 }244 }245 }]246 }247 }248 }249 });250 var sliceSingleElem = Prismic.parseDoc({251 "id":"VQ_hV31Za5EAy02H",252 "uid":null,253 "type":"article",254 "href":"http://toto.wroom.dev/api/documents/search?ref=VQ_uWX1Za0oCy46m&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22VQ_hV31Za5EAy02H%22%29+%5D%5D",255 "tags":[],256 "slugs":["une-activite"],257 "linked_documents":[],258 "data":{259 "article":{260 "blocks":{261 "type":"SliceZone",262 "value":[{263 "type":"Slice",264 "slice_type": "features",265 "value": {266 "type":"StructuredText",267 "value":[{268 type: "heading2",269 text: "As seen by fine pastry as a field",270 spans: []271 }, {272 "type":"paragraph",273 "text":"C'est un bloc content",274 "spans":[]275 }]276 }277 }]278 }279 }280 }281 });282 var sliceWithSingleComposite = Prismic.parseDoc({283 "id":"VQ_hV31Za5EAy02H",284 "uid":null,285 "type":"article",286 "href":"http://toto.wroom.dev/api/documents/search?ref=VQ_uWX1Za0oCy46m&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22VQ_hV31Za5EAy02H%22%29+%5D%5D",287 "tags":[],288 "slugs":["une-activite"],289 "linked_documents":[],290 "data":{291 "article":{292 "blocks":{293 "type":"SliceZone",294 "value":[{295 "type": "Slice",296 "slice_type": "ma-nouvelle-slice",297 "slice_label": null,298 "repeat": [299 {300 "text": {301 "type": "StructuredText",302 "value": [303 {304 "type": "paragraph",305 "text": "some text",306 spans: []307 }308 ]309 }310 }311 ],312 "non-repeat": {313 "text": {314 "type": "StructuredText",315 "value": [316 {317 "type": "heading2",318 "text": "some other text",319 spans: []320 }321 ]322 }323 }324 }]325 }326 }327 }328 });329 // Testing get First title on doc level.330 assert.equal(doc.getFirstTitle().text, "As seen by fine pastry as a field");331 var slices = doc.getSliceZone('article.blocks');332 assert.equal(slices.getFirstTitle().text, "As seen by fine pastry as a field");333 var slicesWithSingleElem = sliceSingleElem.getSliceZone('article.blocks');334 assert.equal(slicesWithSingleElem.getFirstTitle().text, "As seen by fine pastry as a field");335 var compositeSlice = sliceWithSingleComposite.getSliceZone('article.blocks');336 assert.equal(compositeSlice.getFirstTitle().text, "some other text");337 done();338 });339 it('getFirstParagraph in slice zone works', function (done) {340 var doc = Prismic.parseDoc({341 "id":"VQ_hV31Za5EAy02H",342 "uid":null,343 "type":"article",344 "href":"http://toto.wroom.dev/api/documents/search?ref=VQ_uWX1Za0oCy46m&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22VQ_hV31Za5EAy02H%22%29+%5D%5D",345 "tags":[],346 "slugs":["une-activite"],347 "linked_documents":[],348 "data":{349 "article":{350 "blocks":{351 "type":"SliceZone",352 "value":[{353 "type":"Slice",354 "slice_type": "features",355 "value":{356 "type":"Group",357 "value":[{358 "illustration":{359 "type":"Image",360 "value":{361 "main":{362 "url":"https://wroomdev.s3.amazonaws.com/toto/db3775edb44f9818c54baa72bbfc8d3d6394b6ef_hsf_evilsquall_first_in_slice.jpg",363 "alt":"",364 "copyright":"",365 "dimensions":{"width":4285,"height":709}366 },367 "views":{}368 }369 },370 "title":{371 "type":"Text",372 "value":"c'est un bloc features"373 }374 }]375 }376 },{377 "type":"Slice",378 "slice_type":"text",379 "value":{380 "type":"StructuredText",381 "value":[{382 type: "heading2",383 text: "As seen by fine pastry as a field",384 spans: []385 }, {386 "type":"paragraph",387 "text":"C'est un bloc content",388 "spans":[]389 }]390 }391 }]392 }393 }394 }395 });396 var sliceSingleElem = Prismic.parseDoc({397 "id":"VQ_hV31Za5EAy02H",398 "uid":null,399 "type":"article",400 "href":"http://toto.wroom.dev/api/documents/search?ref=VQ_uWX1Za0oCy46m&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22VQ_hV31Za5EAy02H%22%29+%5D%5D",401 "tags":[],402 "slugs":["une-activite"],403 "linked_documents":[],404 "data":{405 "article":{406 "blocks":{407 "type":"SliceZone",408 "value":[{409 "type":"Slice",410 "slice_type": "features",411 "value": {412 "type":"StructuredText",413 "value":[{414 type: "heading2",415 text: "As seen by fine pastry as a field",416 spans: []417 }, {418 "type":"paragraph",419 "text":"C'est un bloc content",420 "spans":[]421 }]422 }423 }]424 }425 }426 }427 });428 // Testing get First paragraph on doc level.429 assert.equal(doc.getFirstParagraph().text, "C'est un bloc content");430 var slices = doc.getSliceZone('article.blocks');431 assert.equal(slices.getFirstParagraph().text, "C'est un bloc content");432 var slicesWithSingleElem = sliceSingleElem.getSliceZone('article.blocks');433 assert.equal(slicesWithSingleElem.getFirstParagraph().text, "C'est un bloc content");434 done();435 });436});437describe('StructuredText', function() {438 it('asHtml handles embeds and lists', function () {439 return Prismic.api(microRepository).then(function (Api) {440 return Api.getByID('WHx-gSYAAMkyXYX_').then(function (doc) {441 assert.equal(442 doc.getStructuredText('all.stext').asHtml(getLinkResolver()).slice(0, 100),443 '<p>normal <strong>b</strong> <em>i</em> <strong><em>bi</em></strong> <a href="http://prismic.io">lin'444 );445 });446 });447 });448 it('asText works', function () {449 return Prismic.api(microRepository).then(function (Api) {450 return Api.getByID('WHx-gSYAAMkyXYX_').then(function (doc) {451 assert.equal(452 doc.getStructuredText('all.stext').asText().slice(0, 100),453 "normal b i bi linkweb linkdoc linkmedia preformatted h1 h2 h3 h4 h5 h6"454 );455 });456 });457 });458/*459 it('asHtml handles preformatted', function (done) {460 Prismic.api(microRepository, function (err, Api) {461 if (err) { done(err); return; }462 Api.form('everything').query('[[:d = at(document.id, "UrDejAEAAFwMyrW9")]]').ref(Api.master()).submit(function (err, documents) {463 if (err) { done(err); return; }464 assert.equal(465 documents.results[0].getStructuredText('doc.content').asHtml(getLinkResolver()),466 '<p>Meta-micro gets installed pretty much like any javascript library:</p><ol><li><a href=\"/testing_url/U0w8OwEAACoAQEvB/download-meta-micro\">download</a> the .js file: get the minified one, unless the framework you\'re using minifies your .js files automatically.</li><li>add a link towards the file in your webpage\'s head.</li></ol><p>The link might look like this, anywhere inside your head tag:</p><pre>&lt;script type=\"text/javascript\" src=\"meta-micro.min.js\"&gt;&lt;/script&gt;</pre><p>You\'re all set!</p>'467 );468 done();469 });470 });471 });472 it('Test backward-compatibility with passing a ctx instead of just a linkResolver', function (done) {473 Prismic.api(microRepository, function (err, Api) {474 if (err) { done(err); return; }475 Api.form('everything').query('[[:d = at(document.id, "UrDejAEAAFwMyrW9")]]').ref(Api.master()).submit(function (err, documents) {476 if (err) { done(err); return; }477 assert.equal(478 documents.results[0].getStructuredText('doc.content').asHtml({479 api: undefined,480 ref: { ref: 'XXXXX', label: 'Future release', isMaster: false },481 maybeRef: 'XXXXX',482 oauth: function () {},483 linkResolver: function (ctx, doc, isBroken) {484 if (isBroken) return '#broken';485 return "/testing_url/" + doc.id + "/" + doc.slug + ( ctx.maybeRef ? '?ref=' + ctx.maybeRef : '' );486 }487 }),488 '<p>Meta-micro gets installed pretty much like any javascript library:</p><ol><li><a href=\"/testing_url/U0w8OwEAACoAQEvB/download-meta-micro?ref=XXXXX\">download</a> the .js file: get the minified one, unless the framework you\'re using minifies your .js files automatically.</li><li>add a link towards the file in your webpage\'s head.</li></ol><p>The link might look like this, anywhere inside your head tag:</p><pre>&lt;script type=\"text/javascript\" src=\"meta-micro.min.js\"&gt;&lt;/script&gt;</pre><p>You\'re all set!</p>');489 done();490 });491 });492 });493 it('asHtml handles spans', function (done) {494 Prismic.api(microRepository, function (err, Api) {495 if (err) { done(err); return; }496 Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbt")]]').ref(Api.master()).submit(function (err, documents) {497 if (err) { done(err); return; }498 assert.equal(documents.results[0].getStructuredText('blog-post.body').asHtml(), '<h1>The end of a chapter the beginning of a new one</h1><p class="block-img"><img src="https://prismic-io.s3.amazonaws.com/lesbonneschoses/8181933ff2f5032daff7d732e33a3beb6f57e09f.jpg" alt=\"\"></p><p>Jean-Michel Pastranova, the founder of <em>Les Bonnes Choses</em>, and creator of the whole concept of modern fine pastry, has decided to step down as the CEO and the Director of Workshops of <em>Les Bonnes Choses</em>, to focus on other projects, among which his now best-selling pastry cook books, but also to take on a primary role in a culinary television show to be announced later this year.</p><p>"I believe I\'ve taken the <em>Les Bonnes Choses</em> concept as far as it can go. <em>Les Bonnes Choses</em> is already an entity that is driven by its people, thanks to a strong internal culture, so I don\'t feel like they need me as much as they used to. I\'m sure they are greater ways to come, to innovate in pastry, and I\'m sure <em>Les Bonnes Choses</em>\'s coming innovation will be even more mind-blowing than if I had stayed longer."</p><p>He will remain as a senior advisor to the board, and to the workshop artists, as his daughter Selena, who has been working with him for several years, will fulfill the CEO role from now on.</p><p>"My father was able not only to create a revolutionary concept, but also a company culture that puts everyone in charge of driving the company\'s innovation and quality. That gives us years, maybe decades of revolutionary ideas to come, and there\'s still a long, wonderful path to walk in the fine pastry world."</p>');499 done();500 });501 }, previewToken);502 });503 it('asHtml handles span Link.web', function (done) {504 Prismic.api(microRepository, function (err, Api) {505 if (err) { done(err); return; }506 Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbW")]]').ref(Api.master()).submit(function (err, documents) {507 if (err) { done(err); return; }508 assert.equal(documents.results[0].getStructuredText('job-offer.profile').asHtml(), '<p>As a company whose marketing is very content-centric, we expect our Content Director to have a tremendous experience, both in content strategy, and in content writing. We expect our applicants to show off some of the content strategies they set up themselves, explaining their choices, and to provide amazing contents they personally wrote.</p><p>Our contents get flexibly powerfully shared on various supports: our site, our in-store printed magazine, our mobile apps, our mailings ... Our Content Director must have experience with all of those, and with using modern adaptive content managers such as <a href=\"http://prismic.io\">prismic.io</a>.</p>');509 done();510 });511 }, previewToken);512 });513 it('asHtml handles span Link.document', function (done) {514 Prismic.api(microRepository, function (err, Api) {515 if (err) { done(err); return; }516 Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbl")]]').ref(Api.master()).submit(function (err, documents) {517 if (err) { done(err); return; }518 assert.equal(documents.results[0].getStructuredText('blog-post.body').asHtml(getLinkResolver('XXXXX')), '<h1>Our world-famous Pastry Art Brainstorm event</h1><p class=\"block-img\"><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg\" alt=\"\"></p><p>Each year, <em>Les Bonnes Choses</em> organizes a world-famous two-day event called the \"Pastry Art Brainstorm\", and which is the perfect excuse for every fine pastry artist in the world to exercise their art, and build their skills up. The event is a multiple win-win operation, at many levels: see what the event is, as seen by many point of views.</p><h2>As seen by the top pastry artists worldwide</h2><p>The event always starts with half a day of conference talks, given by the most insightful pastry artists in the world, selected for having made tremendous achievements in pastry that year. The list of invited guest speakers is decided jointly by the <em>Les Bonnes Choses</em> staff and the Fine Pastry Magazine editors.</p><p>This is great for the speakers, who get an occasion to share their work, and have people build up on it with them.</p><h2>As seen by the pastry professionals</h2><p>After half a day of thoughtful conference, the professionals will get to put what they learned to good use, and mingle with the best artists worldwide to make the most daring pastries together. There are no set rules about who does what during this giant innovation workshop, and many crazy ideas get created out of thin air. As a virtually infinite amount of ingredients is provided by the <em>Les Bonnes Choses</em> staff, many unexpected pastries happen on that day, and professionals taste each other\'s creations, and provide relevant feedback to each other. Most pieces get showcased to the amateur audience as well, who get invited to taste some of the pieces.</p><p>At noon on the second day, teams are expected to subscribe to our Pastry Art Challenge, during which they will make the best possible pastry, judged on many aspects (originality, taste, looks, ...) by a jury of amateurs and professionals. The team members of the three winning pieces share a substantial prize, and their pastries may even join the Les Bonnes Choses catalogue, and be offered in all the <em>Les Bonnes Choses</em> shops worldwide!</p><h2>As seen by the pastry amateurs</h2><p>The conference is limited with a reasonable fee; but the showcase is open to everyone, although visitors are often expected to pay the pastry chefs for the pastries they taste. The educated amateurs spend their day tasting the most daring pieces, giving some appreciated feedback to their chefs, and challenging their own tastebuds. The novice amateurs usually get a once-in-a-lifetime experience, and often mention being blown away by how rich the fine pastry art can be. All in all, every one goes home with a smile on their faces!</p><h2>As seen by the Les Bonnes Choses interns</h2><p>Every year, we recruit a very limited amount of interns, who get aboard a <a href=\"/testing_url/UlfoxUnM0wkXYXbu/les-bonnes-chosess-internship-a-testimony?ref=XXXXX\">life-defining adventure around fine pastries</a>, discovering <em>Les Bonnes Choses</em> during half a year, with part of this time spent in one of our shops abroad. We always manage to get them on board at a time when we know they will be able to attend a Fine Pastry Brainstorm, because we consider it is a very defining element in the experience of being part of <em>Les Bonnes Choses</em>.</p><p>Not only do we invite them to the event (whatever the country they are stationed in when the event happens), but we give them a front-row seat! They are part of the jury for the Fine Pastry Challenge, they are introduced to every speaker as the next generation of pastry (thus having the occasion to learn even more, directly from them).</p><h2>As seen by fine pastry as a field</h2><p>There wasn\'t really an international occasion for pastry artists to join and share, before <em>Les Bonnes Choses</em> came up with the first Fine Pastry Brainstorm, in 2006. Fine Pastry Magazine\'s first edition was out in 2004, and initiated the idea that pastry art needed to be shared better between professionals. But a proper event to meet up in person was missing, and <em>Les Bonnes Choses</em> is proud to be the one to have come up with it first.</p><p>Since then, more local initiatives have been started (notably in Argentina, and Canada), but none comes close to the size of <em>Les Bonnes Choses</em>\'s international Fine Pastry Brainstorm.</p><h2>As seen by <em>Les Bonnes Choses</em></h2><p>As the almost only sponsor of every edition of the event, <em>Les Bonnes Choses</em> makes sure enough ingredients are available for everyone, rents the premises, makes sure the speakers are as comfortable as possible, and takes care of the whole organization! But through the operation, <em>Les Bonnes Choses</em> gains much more than any sponsoring can buy: not only does it get to secure <em>Les Bonnes Choses</em> as the world reference in pastry arts, but it also allows them to claim rightfully that they do offer in their shops the best pastries, created by the world top artists indeed.</p>');519 done();520 });521 }, previewToken);522 });523 it('asHtml with custom serializer', function (done) {524 Prismic.api(microRepository, function (err, Api) {525 if (err) { done(err); return; }526 Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbl")]]').ref(Api.master()).submit(function (err, documents) {527 if (err) { done(err); return; }528 var htmlSerializer = function (element, content) {529 if (element.type == "image") {530 return '<img src="' + element.url + '" alt="' + (element.alt || "") + '">';531 }532 if (element.type == "hyperlink") {533 return '<a class="some-link" href="' + element.url + '">' + content + '</a>';534 }535 return null;536 };537 assert.equal(538 documents.results[0].getStructuredText('blog-post.body').asHtml(getLinkResolver(), htmlSerializer),539 '<h1>Our world-famous Pastry Art Brainstorm event</h1>' +540 '<img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg\" alt=\"\">' +541 '<p>Each year, <em>Les Bonnes Choses</em> organizes a world-famous two-day event called the \"Pastry Art Brainstorm\", and which is the perfect excuse for every fine pastry artist in the world to exercise their art, and build their skills up. The event is a multiple win-win operation, at many levels: see what the event is, as seen by many point of views.</p>' +542 '<h2>As seen by the top pastry artists worldwide</h2>' +543 '<p>The event always starts with half a day of conference talks, given by the most insightful pastry artists in the world, selected for having made tremendous achievements in pastry that year. The list of invited guest speakers is decided jointly by the <em>Les Bonnes Choses</em> staff and the Fine Pastry Magazine editors.</p>' +544 '<p>This is great for the speakers, who get an occasion to share their work, and have people build up on it with them.</p>' +545 '<h2>As seen by the pastry professionals</h2>' +546 '<p>After half a day of thoughtful conference, the professionals will get to put what they learned to good use, and mingle with the best artists worldwide to make the most daring pastries together. There are no set rules about who does what during this giant innovation workshop, and many crazy ideas get created out of thin air. As a virtually infinite amount of ingredients is provided by the <em>Les Bonnes Choses</em> staff, many unexpected pastries happen on that day, and professionals taste each other\'s creations, and provide relevant feedback to each other. Most pieces get showcased to the amateur audience as well, who get invited to taste some of the pieces.</p>' +547 '<p>At noon on the second day, teams are expected to subscribe to our Pastry Art Challenge, during which they will make the best possible pastry, judged on many aspects (originality, taste, looks, ...) by a jury of amateurs and professionals. The team members of the three winning pieces share a substantial prize, and their pastries may even join the Les Bonnes Choses catalogue, and be offered in all the <em>Les Bonnes Choses</em> shops worldwide!</p>' +548 '<h2>As seen by the pastry amateurs</h2>' +549 '<p>The conference is limited with a reasonable fee; but the showcase is open to everyone, although visitors are often expected to pay the pastry chefs for the pastries they taste. The educated amateurs spend their day tasting the most daring pieces, giving some appreciated feedback to their chefs, and challenging their own tastebuds. The novice amateurs usually get a once-in-a-lifetime experience, and often mention being blown away by how rich the fine pastry art can be. All in all, every one goes home with a smile on their faces!</p>' +550 '<h2>As seen by the Les Bonnes Choses interns</h2>' +551 '<p>Every year, we recruit a very limited amount of interns, who get aboard a <a class="some-link" href=\"/testing_url/UlfoxUnM0wkXYXbu/les-bonnes-chosess-internship-a-testimony\">life-defining adventure around fine pastries</a>, discovering <em>Les Bonnes Choses</em> during half a year, with part of this time spent in one of our shops abroad. We always manage to get them on board at a time when we know they will be able to attend a Fine Pastry Brainstorm, because we consider it is a very defining element in the experience of being part of <em>Les Bonnes Choses</em>.</p>' +552 '<p>Not only do we invite them to the event (whatever the country they are stationed in when the event happens), but we give them a front-row seat! They are part of the jury for the Fine Pastry Challenge, they are introduced to every speaker as the next generation of pastry (thus having the occasion to learn even more, directly from them).</p>' +553 '<h2>As seen by fine pastry as a field</h2>' +554 '<p>There wasn\'t really an international occasion for pastry artists to join and share, before <em>Les Bonnes Choses</em> came up with the first Fine Pastry Brainstorm, in 2006. Fine Pastry Magazine\'s first edition was out in 2004, and initiated the idea that pastry art needed to be shared better between professionals. But a proper event to meet up in person was missing, and <em>Les Bonnes Choses</em> is proud to be the one to have come up with it first.</p>' +555 '<p>Since then, more local initiatives have been started (notably in Argentina, and Canada), but none comes close to the size of <em>Les Bonnes Choses</em>\'s international Fine Pastry Brainstorm.</p>' +556 '<h2>As seen by <em>Les Bonnes Choses</em></h2>' +557 '<p>As the almost only sponsor of every edition of the event, <em>Les Bonnes Choses</em> makes sure enough ingredients are available for everyone, rents the premises, makes sure the speakers are as comfortable as possible, and takes care of the whole organization! But through the operation, <em>Les Bonnes Choses</em> gains much more than any sponsoring can buy: not only does it get to secure <em>Les Bonnes Choses</em> as the world reference in pastry arts, but it also allows them to claim rightfully that they do offer in their shops the best pastries, created by the world top artists indeed.</p>'558 );559 done();560 });561 }, previewToken);562 });563 it('getFirstImage works', function (done) {564 Prismic.api(microRepository, function (err, Api) {565 if (err) { done(err); return; }566 Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbl")]]').ref(Api.master()).submit(function (err, documents) {567 if (err) { done(err); return; }568 assert.equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().url, "https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg");569 assert.equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().alt, null);570 assert.equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().height, 427);571 assert.equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().width, 640);572 assert.equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().asHtml(),573 '<img src="https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg" width="640" height="427" alt="">');574 done();575 });576 }, previewToken);577 });578*/579 it('asHtml handles span Link.file', function () {580 var jsonString = '{"type":"StructuredText","value":[{"type":"paragraph","text":"2012 Annual Report","spans":[{"start":0,"end":18,"type":"hyperlink","data":{"type":"Link.file","value":{"file":{"name":"2012_annual.report.pdf","kind":"document","url":"https://prismic-io.s3.amazonaws.com/annual.report.pdf","size":"1282484"}}}}]},{"type":"paragraph","text":"2012 Annual Budget","spans":[{"start":0,"end":18,"type":"hyperlink","data":{"type":"Link.file","value":{"file":{"name":"2012_smec.annual.budget.pdf","kind":"document","url":"https://prismic-io.s3.amazonaws.com/annual.budget.pdf","size":"59229"}}}}]},{"type":"paragraph","text":"2015 Vision & Strategic Plan","spans":[{"start":0,"end":28,"type":"hyperlink","data":{"type":"Link.file","value":{"file":{"name":"2015_vision.strategic.plan_.sm_.pdf","kind":"document","url":"https://prismic-io.s3.amazonaws.com/vision.strategic.plan_.sm_.pdf","size":"1969956"}}}}]}]}';581 var jsonObject = JSON.parse(jsonString);582 assert.equal(Prismic.Fragments.initField(jsonObject).asHtml(), '<p><a href=\"https://prismic-io.s3.amazonaws.com/annual.report.pdf\">2012 Annual Report</a></p><p><a href=\"https://prismic-io.s3.amazonaws.com/annual.budget.pdf\">2012 Annual Budget</a></p><p><a href=\"https://prismic-io.s3.amazonaws.com/vision.strategic.plan_.sm_.pdf\">2015 Vision &amp; Strategic Plan</a></p>');583 });584 it('Proper escaping in asHtml', function (done) {585 var jsonString = "{ \"type\": \"StructuredText\", \"value\": [ { \"type\": \"paragraph\", \"text\": \"<not a real tag>\\nsome text\", \"spans\": [] } ]}";586 var jsonObject = JSON.parse(jsonString);587 var text = Prismic.Fragments.initField(jsonObject);588 assert.equal(589 text.asHtml(),590 "<p>&lt;not a real tag&gt;<br>some text</p>"591 );592 done();593 });594});595describe('Various fragment types', function() {596 // it('Handles multiple fields', function () {597 // return Prismic.api(microRepository, previewToken).then(function (Api) {598 // return Api.getByID('WHx-gSYAAMkyXYX_').then(function (doc) {599 // assert.equal(doc.getAll('all.slices.link_document')[0].asHtml(getLinkResolver()), '<a href="/testing_url/UlfoxUnM0wkXYXbm/tips-to-dress-a-pastry">/testing_url/UlfoxUnM0wkXYXbm/tips-to-dress-a-pastry</a>');600 // done();601 // });602 // });603 // });604 it('ImageViews are well retrieved', function () {605 return Prismic.api(microRepository, previewToken).then(function (Api) {606 return Api.getByID('WHx-gSYAAMkyXYX_').then(function (doc) {607 assert.equal(doc.getImageView('all.image', 'main').asHtml(), '<img src="https://prismic-io.s3.amazonaws.com/micro/e185bb021862c2c03a96bea92e170830908c39a3_thermometer.png" width="600" height="600" alt="" copyright="">');608 assert.equal(doc.getImageView('all.image', 'small').asHtml(), '<img src="https://prismic-io.s3.amazonaws.com/micro/5f4a19be1fd2edeaf7bc8123a3d67ee87a8446ef_thermometer.png" width="128" height="128" alt="" copyright="">');609 });610 });611 });612 it('GeoPoint is retrieved', function () {613 return Prismic.api(microRepository).then(function (Api) {614 return Api.getByID('WHx-gSYAAMkyXYX_').then(function (doc) {615 var html = '<div class="geopoint"><span class="latitude">48.87369154037622</span><span class="longitude">2.3618245124816895</span></div>';616 assert.equal(doc.getGeoPoint('all.geopoint').asHtml(), html);617 });618 });619 });620 it('Date and Timestamp are parsed correctly', function () {621 var json = JSON.parse('{ "id": "UlfoxUnM0wkXYXbm", "type": "blog-post", "href": "https://lesbonneschoses-vcerzcwaaohojzo.prismic.io/api/documents/...",' +622 '"tags": [], "slugs": [], "linked_documents": [],' +623 '"data": { "blog-post": {' +624 '"date": { "type": "Date", "value": "2013-08-17" },' +625 '"timestamp": { "type": "Timestamp", "value": "2014-10-06T12:24:36+0000" } ' +626 '}}}');627 var doc = Prismic.parseDoc(json);628 var date = doc.getDate("blog-post.date");629 assert.equal(date.getFullYear(), 2013);630 var ts = doc.getTimestamp("blog-post.timestamp");631 assert.equal(ts.getFullYear(), 2014);632 });633 it('Block fragments are accessible, loopable, and serializable', function (done) {634 Prismic.api(microRepository, function (err, Api) {635 if (err) { done(err); return; }636 Api.form('everything').query('[[:d = at(document.id, "UrDndQEAALQMyrXF")]]').ref(Api.master()).submit(function (err, documents) {637 if (err) { done(err); return; }638 // Group fragments are accessible639 assert.equal(documents.results[0].getGroup('docchapter.docs').toArray()[0].getLink('linktodoc').value.document.type, 'doc');640 // Group fragments are loopable641 var slugs = "";642 for (var i = 0; i < documents.results[0].getGroup('docchapter.docs').toArray().length; i++) {643 slugs += documents.results[0].getGroup('docchapter.docs').toArray()[i].getLink('linktodoc').value.document.slug + ' ';644 }645 assert.equal(slugs.trim(), 'with-jquery with-bootstrap');646 // Group fragments are serializable when asHtml is called directly on them647 assert.equal(documents.results[0].getGroup('docchapter.docs').asHtml(getLinkResolver()),648 '<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDofwEAALAdpbNH/with-jquery\">/testing_url/UrDofwEAALAdpbNH/with-jquery</a></section>' +649 '<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap\">/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap</a></section>');650 // Group fragments are serializable when as Html is called on a document651 assert.equal(documents.results[0].asHtml(getLinkResolver()),652 '<section data-field=\"docchapter.title\"><h1>Using with other projects</h1></section>' +653 '<section data-field=\"docchapter.intro\"><p>As advertised, meta-micro knows how to stay out of the way of the rest of your application. Here are some cases of how to use it with some of the most used open-source projects in JavaScript.</p></section>' +654 '<section data-field=\"docchapter.priority\"><span>500</span></section>' +655 '<section data-field=\"docchapter.docs\">' +656 '<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDofwEAALAdpbNH/with-jquery\">/testing_url/UrDofwEAALAdpbNH/with-jquery</a></section>' +657 '<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap">/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap</a></section>' +658 '</section>');659 done();660 });661 });662 });663 it('Slices correctly parsed and serializable', function () {664 var doc = Prismic.parseDoc({665 "id":"VQ_hV31Za5EAy02H",666 "uid":null,667 "type":"article",668 "href":"http://toto.wroom.dev/api/documents/search?ref=VQ_uWX1Za0oCy46m&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22VQ_hV31Za5EAy02H%22%29+%5D%5D",669 "tags":[],670 "slugs":["une-activite"],671 "linked_documents":[],672 "data":{673 "article":{674 "activities":{675 "type":"Group",676 "value":[{677 "title":{678 "type":"StructuredText",679 "value":[{680 "type":"paragraph",681 "text":"Une activité",682 "spans":[]683 }]684 },685 "image":{686 "type":"Image",687 "value":{688 "main":{689 "url":"https://wroomdev.s3.amazonaws.com/toto/ce3f52b933c4934a13422e09ed0ff6ad03a29621_hsf_evilsquall.jpg",690 "alt":"",691 "copyright":"",692 "dimensions":{"width":860,"height":640}693 },694 "views":{695 "headline":{696 "url":"https://wroomdev.s3.amazonaws.com/toto/5445d2dcd2b0c541b0406ca867ab3d07b309c944_hsf_evilsquall.jpg",697 "alt":"",698 "copyright":"",699 "dimensions":{"width":570,"height":400}700 }701 }702 }703 },704 "body":{705 "type":"StructuredText",706 "value":[{707 "type":"paragraph",708 "text":"elle est bien",709 "spans":[]710 }]711 }712 }]713 },714 "un_champ_texte":{715 "type":"Text",716 "value":"stuffgg"717 },718 "blocks":{719 "type":"SliceZone",720 "value":[{721 "type":"Slice",722 "slice_type": "features",723 "value":{724 "type":"Group",725 "value":[{726 "illustration":{727 "type":"Image",728 "value":{729 "main":{730 "url":"https://wroomdev.s3.amazonaws.com/toto/db3775edb44f9818c54baa72bbfc8d3d6394b6ef_hsf_evilsquall.jpg",731 "alt":"",732 "copyright":"",733 "dimensions":{"width":4285,"height":709}734 },735 "views":{}736 }737 },738 "title":{739 "type":"Text",740 "value":"c'est un bloc features"741 }742 }]743 }744 },{745 "type":"Slice",746 "slice_type":"text",747 "value":{748 "type":"StructuredText",749 "value":[{750 "type":"paragraph",751 "text":"C'est un bloc content",752 "spans":[]753 }]754 }755 }, {756 "type": "Slice",757 "slice_type": "ma-nouvelle-slice",758 "slice_label": null,759 "repeat": [760 {761 "text": {762 "type": "StructuredText",763 "value": [764 {765 "type": "paragraph",766 "text": "C'est du repeat",767 spans: []768 }769 ]770 }771 }772 ],773 "non-repeat": {774 "text": {775 "type": "StructuredText",776 "value": [777 {778 "type": "heading2",779 "text": "C'est du non repeat",780 spans: []781 }782 ]783 }784 }785 }]786 }787 }788 }789 });790 var slices = doc.getSliceZone('article.blocks');791 assert.equal(slices.asText(getLinkResolver()), "c'est un bloc features\n\nC'est un bloc content\nC\'est du non repeat\nC\'est du repeat\n\n");792 assert.equal(slices.asHtml(getLinkResolver()), '<div data-slicetype="features" class="slice"><section data-field="illustration"><img src="https://wroomdev.s3.amazonaws.com/toto/db3775edb44f9818c54baa72bbfc8d3d6394b6ef_hsf_evilsquall.jpg" width="4285" height="709" alt="" copyright=""></section><section data-field="title"><span>c\'est un bloc features</span></section></div><div data-slicetype="text" class="slice"><p>C\'est un bloc content</p></div><div data-slicetype="ma-nouvelle-slice" class="slice"><h2>C\'est du non repeat</h2><section data-field="text"><p>C\'est du repeat</p></section></div>');793 });794 it('Slices correctly handle document links when rendering as text', function () {795 var doc = Prismic.parseDoc({796 "id":"VQ_hV31Za5EAy02H",797 "uid":null,798 "type":"article",799 "href":"http://toto.wroom.dev/api/documents/search?ref=VQ_uWX1Za0oCy46m&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22VQ_hV31Za5EAy02H%22%29+%5D%5D",800 "tags":[],801 "slugs":["une-activite"],802 "linked_documents":[],803 "data":{804 "article":{805 "blocks":{806 "type":"SliceZone",807 "value":[{808 "type":"Slice",809 "slice_type": "link",810 "value":{811 "type":"Link.document",812 "value": {813 "document": {814 "id": "UrDejAEAAFwMyrW9",815 "type": "doc",816 "tags": [],817 "slug": "installing-meta-micro"818 },819 "isBroken": false820 }821 }822 },{823 "type":"Slice",824 "slice_type":"text",825 "value":{826 "type":"StructuredText",827 "value":[{828 "type":"paragraph",829 "text":"C'est un bloc content",830 "spans":[]831 }]832 }833 }]834 }835 }836 }837 });838 var slices = doc.getSliceZone('article.blocks');839 assert.equal(slices.asText(getLinkResolver()), "/testing_url/UrDejAEAAFwMyrW9/installing-meta-micro\nC'est un bloc content\n");840 });841 it('Number correctly null content when rendering as text', function () {842 var doc = Prismic.parseDoc({843 "id":"VQ_hV31Za5EAy02H",844 "uid":null,845 "type":"article",846 "href":"http://toto.wroom.dev/api/documents/search?ref=VQ_uWX1Za0oCy46m&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22VQ_hV31Za5EAy02H%22%29+%5D%5D",847 "tags":[],848 "slugs":["une-activite"],849 "linked_documents":[],850 "data":{851 "article":{852 "number":{853 "type":"Number",854 "value":null855 }856 }857 }858 });859 assert.equal(doc.asText(getLinkResolver()), "");860 });...

Full Screen

Full Screen

fileutils.js

Source:fileutils.js Github

copy

Full Screen

1// Utility functions2var testRanCounter = 0;3var expectedTestCount = 0;4function testHasRun() {5 //alert(testRanCounter);6 ++testRanCounter;7 if (testRanCounter == expectedTestCount) {8 SimpleTest.finish();9 }10}11function testFile(file, contents, test) {12 SimpleTest.requestLongerTimeout(2);13 // Load file using FileReader14 var r = new FileReader();15 r.onload = getFileReaderLoadHandler(contents, contents.length, "FileReader.readAsBinaryString of " + test);16 r.readAsBinaryString(file);17 expectedTestCount++;18 // Load file using URL.createObjectURL and XMLHttpRequest19 var xhr = new XMLHttpRequest;20 xhr.open("GET", URL.createObjectURL(file));21 xhr.onload = getXHRLoadHandler(contents, contents.length, false,22 "XMLHttpRequest load of " + test);23 xhr.overrideMimeType('text/plain; charset=x-user-defined');24 xhr.send();25 expectedTestCount++;26 // Send file to server using FormData and XMLHttpRequest27 xhr = new XMLHttpRequest();28 xhr.onload = function(event) {29 checkMPSubmission(JSON.parse(event.target.responseText),30 [{ name: "hello", value: "world"},31 { name: "myfile",32 value: contents,33 fileName: file.name || "blob",34 contentType: file.type || "application/octet-stream" }]);35 testHasRun();36 }37 xhr.open("POST", "../../html/content/test/form_submit_server.sjs");38 var fd = new FormData;39 fd.append("hello", "world");40 fd.append("myfile", file);41 xhr.send(fd);42 expectedTestCount++;43 // Send file to server using plain XMLHttpRequest44 var xhr = new XMLHttpRequest;45 xhr.open("POST", "file_XHRSendData.sjs");46 xhr.onload = function (event) {47 is(event.target.getResponseHeader("Result-Content-Type"),48 file.type ? file.type : null,49 "request content-type in XMLHttpRequest send of " + test);50 is(event.target.getResponseHeader("Result-Content-Length"),51 file.size,52 "request content-length in XMLHttpRequest send of " + test);53 };54 xhr.addEventListener("load",55 getXHRLoadHandler(contents, contents.length, true,56 "XMLHttpRequest send of " + test),57 false);58 xhr.overrideMimeType('text/plain; charset=x-user-defined');59 xhr.send(file);60 expectedTestCount++;61}62function getFileReaderLoadHandler(expectedResult, expectedLength, testName) {63 return function (event) {64 is(event.target.readyState, FileReader.DONE,65 "[FileReader] readyState in test " + testName);66 is(event.target.error, null,67 "[FileReader] no error in test " + testName);68 // Do not use |is(event.target.result, expectedResult, "...");| that may output raw binary data.69 is(event.target.result.length, expectedResult.length,70 "[FileReader] Length of result in test " + testName);71 ok(event.target.result == expectedResult,72 "[FileReader] Content of result in test " + testName);73 is(event.lengthComputable, true,74 "[FileReader] lengthComputable in test " + testName);75 is(event.loaded, expectedLength,76 "[FileReader] Loaded length in test " + testName);77 is(event.total, expectedLength,78 "[FileReader] Total length in test " + testName);79 testHasRun();80 }81}82function getXHRLoadHandler(expectedResult, expectedLength, statusWorking, testName) {83 return function (event) {84 is(event.target.readyState, 4,85 "[XHR] readyState in test " + testName);86 if (statusWorking) {87 is(event.target.status, 200,88 "[XHR] no error in test " + testName);89 }90 else {91 todo_is(event.target.status, 200,92 "[XHR] no error in test " + testName);93 }94 // Do not use |is(convertXHRBinary(event.target.responseText), expectedResult, "...");| that may output raw binary data.95 var convertedData = convertXHRBinary(event.target.responseText);96 is(convertedData.length, expectedResult.length,97 "[XHR] Length of result in test " + testName);98 ok(convertedData == expectedResult,99 "[XHR] Content of result in test " + testName);100 is(event.lengthComputable, true,101 "[XHR] lengthComputable in test " + testName);102 is(event.loaded, expectedLength,103 "[XHR] Loaded length in test " + testName);104 is(event.total, expectedLength,105 "[XHR] Total length in test " + testName);106 testHasRun();107 }108}109function convertXHRBinary(s) {110 var res = "";111 for (var i = 0; i < s.length; ++i) {112 res += String.fromCharCode(s.charCodeAt(i) & 255);113 }114 return res;115}116function testHasRun() {117 //alert(testRanCounter);118 ++testRanCounter;119 if (testRanCounter == expectedTestCount) {120 SimpleTest.finish();121 }122}123function createFileWithData(fileData) {124 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");125 var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties);126 var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);127 testFile.append("fileAPItestfile2-" + fileNum);128 fileNum++;129 var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);130 outStream.init(testFile, 0x02 | 0x08 | 0x20, // write, create, truncate131 0666, 0);132 outStream.write(fileData, fileData.length);133 outStream.close();134 var fileList = document.getElementById('fileList');135 fileList.value = testFile.path;136 return fileList.files[0];137}138function gc() {139 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");140 window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)141 .getInterface(Components.interfaces.nsIDOMWindowUtils)142 .garbageCollect();143}144function checkMPSubmission(sub, expected) {145 function getPropCount(o) {146 var x, l = 0;147 for (x in o) ++l;148 return l;149 }150 is(sub.length, expected.length,151 "Correct number of items");152 var i;153 for (i = 0; i < expected.length; ++i) {154 if (!("fileName" in expected[i])) {155 is(sub[i].headers["Content-Disposition"],156 "form-data; name=\"" + expected[i].name + "\"",157 "Correct name (A)");158 is (getPropCount(sub[i].headers), 1,159 "Wrong number of headers (A)");160 }161 else {162 is(sub[i].headers["Content-Disposition"],163 "form-data; name=\"" + expected[i].name + "\"; filename=\"" +164 expected[i].fileName + "\"",165 "Correct name (B)");166 is(sub[i].headers["Content-Type"],167 expected[i].contentType,168 "Correct content type (B)");169 is (getPropCount(sub[i].headers), 2,170 "Wrong number of headers (B)");171 }172 // Do not use |is(sub[i].body, expected[i].value, "...");| that may output raw binary data.173 is(sub[i].body.length, expected[i].value.length,174 "Length of correct value");175 ok(sub[i].body == expected[i].value,176 "Content of correct value");177 }178}179function testSlice(file, size, type, contents, fileType) {180 is(file.type, type, fileType + " file is correct type");181 is(file.size, size, fileType + " file is correct size");182 ok(file instanceof File, fileType + " file is a File");183 ok(file instanceof Blob, fileType + " file is also a Blob");184 185 var slice = file.slice(0, size);186 ok(slice instanceof Blob, fileType + " fullsize slice is a Blob");187 ok(!(slice instanceof File), fileType + " fullsize slice is not a File");188 // Test that mozSlice works still.189 slice = file.mozSlice(0, size);190 ok(slice instanceof Blob, fileType + " fullsize slice is a Blob");191 ok(!(slice instanceof File), fileType + " fullsize slice is not a File");192 193 slice = file.slice(0, 1234);194 ok(slice instanceof Blob, fileType + " sized slice is a Blob");195 ok(!(slice instanceof File), fileType + " sized slice is not a File");196 197 slice = file.slice(0, size, "foo/bar");198 is(slice.type, "foo/bar", fileType + " fullsize slice foo/bar type");199 slice = file.slice(0, 5432, "foo/bar");200 is(slice.type, "foo/bar", fileType + " sized slice foo/bar type");201 202 is(slice.slice(0, 10).type, "", fileType + " slice-slice type");203 is(slice.slice(0, 10).size, 10, fileType + " slice-slice size");204 is(slice.slice(0, 10, "hello/world").type, "hello/world", fileType + " slice-slice hello/world type");205 is(slice.slice(0, 10, "hello/world").size, 10, fileType + " slice-slice hello/world size");206 // Start, end, expected size207 var indexes = [[0, size, size],208 [0, 1234, 1234],209 [size-500, size, 500],210 [size-500, size+500, 500],211 [size+500, size+1500, 0],212 [0, 0, 0],213 [1000, 1000, 0],214 [size, size, 0],215 [undefined, undefined, size],216 [0, undefined, size],217 [100, undefined, size-100],218 [-100, undefined, 100],219 [100, -100, size-200],220 [-size-100, undefined, size],221 [-2*size-100, 500, 500],222 [0, -size-100, 0],223 [100, -size-100, 0],224 [50, -size+100, 50],225 [0, 33000, 33000],226 [1000, 34000, 33000],227 ];228 229 for (var i = 0; i < indexes.length; ++i) {230 var sliceContents;231 var testName;232 if (indexes[i][0] == undefined) {233 slice = file.slice();234 sliceContents = contents.slice();235 testName = fileType + " slice()";236 }237 else if (indexes[i][1] == undefined) {238 slice = file.slice(indexes[i][0]);239 sliceContents = contents.slice(indexes[i][0]);240 testName = fileType + " slice(" + indexes[i][0] + ")";241 }242 else {243 slice = file.slice(indexes[i][0], indexes[i][1]);244 sliceContents = contents.slice(indexes[i][0], indexes[i][1]);245 testName = fileType + " slice(" + indexes[i][0] + ", " + indexes[i][1] + ")";246 }247 is(slice.type, "", testName + " type");248 is(slice.size, indexes[i][2], testName + " size");249 is(sliceContents.length, indexes[i][2], testName + " data size");250 testFile(slice, sliceContents, testName);251 }252 // Slice of slice253 var slice = file.slice(0, 40000);254 testFile(slice.slice(5000, 42000), contents.slice(5000, 40000), "file slice slice");255 256 // ...of slice of slice257 slice = slice.slice(5000, 42000).slice(400, 700);258 SpecialPowers.gc();259 testFile(slice, contents.slice(5400, 5700), "file slice slice slice");...

Full Screen

Full Screen

h264FrameSelector.js

Source:h264FrameSelector.js Github

copy

Full Screen

1goog.provide("com.ttProject.frame.h264.H264FrameSelector");2goog.require("com.ttProject.bit.BitLoader");3goog.require("com.ttProject.frame.h264.type.AccessUnitDelimiter");4goog.require("com.ttProject.frame.h264.type.PictureParameterSet");5goog.require("com.ttProject.frame.h264.type.SequenceParameterSet");6goog.require("com.ttProject.frame.h264.type.SupplementalEnhancementInformation");7goog.require("com.ttProject.frame.h264.type.SliceIDR");8goog.require("com.ttProject.frame.h264.type.Slice");9goog.require("com.ttProject.frame.h264.Type");10goog.require("com.ttProject.bit.BitLoader");11goog.require("com.ttProject.bit.Bit1");12goog.require("com.ttProject.bit.Bit2");13goog.require("com.ttProject.bit.Bit5");14goog.require("com.ttProject.frame.base.VideoSelector");15/**16 * @constructor17 */18com.ttProject.frame.h264.H264FrameSelector = function() {19 goog.base(this);20 this._sps = null;21 this._pps = null;22};23goog.inherits(com.ttProject.frame.h264.H264FrameSelector, com.ttProject.frame.base.VideoSelector);24com.ttProject.frame.h264.H264FrameSelector.prototype.select = function(channel, callback) {25 if(channel.size() != 0 && channel.size() == channel.position()) {26 console.log("データがなくなった。");27 callback(null);28 return;29 }30 var _this = this;31 var loader = new com.ttProject.bit.BitLoader(channel);32 var forbiddenZeroBit = new com.ttProject.bit.Bit1();33 var nalRefIdc = new com.ttProject.bit.Bit2();34 var type = new com.ttProject.bit.Bit5();35 loader.load(forbiddenZeroBit, nalRefIdc, type, function() {36 var frame = null;37 switch(type.get()) {38 case com.ttProject.frame.h264.Type.Unspecified1:39 break;40 case com.ttProject.frame.h264.Type.Slice:41 frame = new com.ttProject.frame.h264.type.Slice(forbiddenZeroBit, nalRefIdc, type);42 break;43 case com.ttProject.frame.h264.Type.SliceDataPartitionA:44 break;45 case com.ttProject.frame.h264.Type.SliceDataPartitionB:46 break;47 case com.ttProject.frame.h264.Type.SliceDataPartitionC:48 break;49 case com.ttProject.frame.h264.Type.SliceIDR:50 // ここつくる必要あり。51 frame = new com.ttProject.frame.h264.type.SliceIDR(forbiddenZeroBit, nalRefIdc, type);52 break;53 case com.ttProject.frame.h264.Type.SupplementalEnhancementInformation:54 frame = new com.ttProject.frame.h264.type.SupplementalEnhancementInformation(forbiddenZeroBit, nalRefIdc, type);55 break;56 case com.ttProject.frame.h264.Type.SequenceParameterSet:57 frame = new com.ttProject.frame.h264.type.SequenceParameterSet(forbiddenZeroBit, nalRefIdc, type);58 _this._sps = frame;59 break;60 case com.ttProject.frame.h264.Type.PictureParameterSet:61 frame = new com.ttProject.frame.h264.type.PictureParameterSet(forbiddenZeroBit, nalRefIdc, type);62 _this._pps = frame;63 break;64 case com.ttProject.frame.h264.Type.AccessUnitDelimiter:65 frame = new com.ttProject.frame.h264.type.AccessUnitDelimiter(forbiddenZeroBit, nalRefIdc, type);66 break;67 case com.ttProject.frame.h264.Type.EndOfSequence:68 break;69 case com.ttProject.frame.h264.Type.EndOfStream:70 break;71 case com.ttProject.frame.h264.Type.FilterData:72 break;73 case com.ttProject.frame.h264.Type.SequenceParameterSetExtension:74 break;75 case com.ttProject.frame.h264.Type.PrefixNalUnit:76 break;77 case com.ttProject.frame.h264.Type.SubsetSequenceParameterSet:78 break;79 case com.ttProject.frame.h264.Type.Reserved1:80 break;81 case com.ttProject.frame.h264.Type.Reserved2:82 break;83 case com.ttProject.frame.h264.Type.Reserved3:84 break;85 case com.ttProject.frame.h264.Type.CodedSliceAuxiliary:86 break;87 case com.ttProject.frame.h264.Type.CodedSliceExtension:88 break;89 case com.ttProject.frame.h264.Type.CodedSliceForDepthView:90 break;91 case com.ttProject.frame.h264.Type.Reserved4:92 break;93 case com.ttProject.frame.h264.Type.Reserved5:94 break;95 case com.ttProject.frame.h264.Type.Unspecified2:96 break;97 case com.ttProject.frame.h264.Type.Unspecified3:98 break;99 case com.ttProject.frame.h264.Type.Unspecified4:100 break;101 case com.ttProject.frame.h264.Type.Unspecified5:102 break;103 case com.ttProject.frame.h264.Type.Unspecified6:104 break;105 case com.ttProject.frame.h264.Type.Unspecified7:106 break;107 case com.ttProject.frame.h264.Type.Unspecified8:108 break;109 case com.ttProject.frame.h264.Type.Unspecified9:110 break;111 default:112 throw new Error("想定外のframeでした。:" + type.get());113 };114 if(frame == null) {115 throw new Error("frameの実体が作成されていませんでした。:" + type.get());116 }117 _this.setup(frame);118 if(!(frame instanceof com.ttProject.frame.h264.type.SequenceParameterSet)) {119 frame.setSps(_this._sps);120 if(!(frame instanceof com.ttProject.frame.h264.type.PictureParameterSet)) {121 frame.setPps(_this._pps);122 }123 }124 frame.minimumLoad(channel, function() {125 callback(frame);126 });127 });...

Full Screen

Full Screen

category_model.js

Source:category_model.js Github

copy

Full Screen

...36 , 'compensation', 'partTime', 'telecommute', 'contract', 'internship', 'nonprofit'];37 switch(parentCode) {38 case 'RRRR':39 if($.inArray(category, ['RCRE', 'RLOT', 'RPNS']) == -1)40 return (type.slice(0, 4))41 else if (category !== 'RLOT')42 return(type.slice(3, 4));43 break;44 case 'VVVV': return(type.slice(4, 21)); break;45 case 'PPPP': return(type.slice(21, 23)); break;46 case 'JJJJ': return(type.slice(23, 29)); break;47 case 'all': return([]); break;48 default:49 break;50 }51 },52 hasPrice : function () {53 return _.indexOf(this.CATEGORIES_WITH_PRICE, this.get("code")) > -1;54 },55 getOptions : function () {56 },57 getCategoryByName : function (name) {58 if (this.get("name") == name) {59 return this;60 }...

Full Screen

Full Screen

Others.js

Source:Others.js Github

copy

Full Screen

...4async function createOthers(type, name) {5 try {6 await Validator.isIOExpress();7 try {8 await Validator.ioExpressFileExists((type[type.length-1] !== 's') ? type.charAt(0).toUpperCase() + type.slice(1) + 's' : type.charAt(0).toUpperCase() + type.slice(1), '', `${name}.${type}.js`);9 console.log(`You are trying to create a ${type} that already exists.`);10 return -1;11 } catch (e) {12 let dummyFile = fs.readFileSync(path.join(__dirname, '../dummy', `${type}.js`)).toString();13 let dummyFileTest = fs.readFileSync(path.join(__dirname, '../dummy', `${type}.spec.js`)).toString();14 if (type === 'middleware') {15 dummyFile = dummyFile.replace(/MIDDLEWARE/g, name);16 dummyFileTest = dummyFileTest.replace(/MIDDLEWARE/g, name);17 dummyFileTest = dummyFileTest.replace(`./${ name }`, `./${ name }.middleware`);18 }19 if (type === 'model') {20 dummyFile = dummyFile.replace('schemaName', name);21 dummyFileTest = dummyFileTest.replace(/MODEL/g, name);22 dummyFileTest = dummyFileTest.replace(`./${name}`, `./${name}.model`);23 dummyFileTest = dummyFileTest.replace(/TESTNAME/g, `${name.charAt(0).toUpperCase() + name.slice(1)}Model`);24 dummyFileTest = dummyFileTest.replace(/NEWDATA/g, `new${name.charAt(0).toUpperCase() + name.slice(1)}Model`);25 }26 fs.writeFileSync(path.join(process.cwd(), 'src', type + 's', `${name}.${type}.js`), dummyFile)27 fs.writeFileSync(path.join(process.cwd(), 'src', type + 's', `${name}.${type}.spec.js`), dummyFileTest)28 console.log(`${type.charAt(0).toUpperCase() + type.slice(1)} created : src/${type}s/${name}.${type}.js`);29 console.log(`${type.charAt(0).toUpperCase() + type.slice(1)} Test created : src/${type}s/${name}.${type}.spec.js`);30 return -1;31 }32 } catch (e) {33 console.log(`Run 'xprs create' command from a valid 'IO Express' project root!`);34 return -1;35 }36}...

Full Screen

Full Screen

packer.js

Source:packer.js Github

copy

Full Screen

...11 dd01: 'simple.discovery_response',12 dd02: 'simple.poweron',13 }14 var loadPacketStructure = function(type, value = false){15 if(type.slice(0, 6) == 'simple'){16 return SimplePacket(type.slice(7), value);17 } else if(type.slice(0, 7) == 'message'){18 return MessagePacket(type.slice(8), value);19 } else {20 Debug('[packet/packer.js] Packet format not found: ', type.toString('hex'));21 return false22 }23 }24 var packet_type = type.slice(0,2).toString('hex')25 var structure = ''26 if(packet_type in Types){27 // We got a packet that we need to unpack28 var packet_value = type;29 type = Types[packet_type];30 structure = loadPacketStructure(type, packet_value)31 } else {32 structure = loadPacketStructure(type)33 }34 return {35 type: type,36 structure: structure,37 set: function(key, value, protected_payload = false){38 this.structure.set(key, value, protected_payload)...

Full Screen

Full Screen

sliceIDR.js

Source:sliceIDR.js Github

copy

Full Screen

1goog.provide("com.ttProject.frame.h264.type.SliceIDR");2goog.require("com.ttProject.frame.h264.SliceFrame");3goog.require("com.ttProject.util.ArrayUtil");4/**5 * @constructor6 */7com.ttProject.frame.h264.type.SliceIDR = function(forbiddenZeroBit, nalRefIdc, type) {8 goog.base(this, forbiddenZeroBit, nalRefIdc, type);9 this.setKeyFrame(true);10 this._buffer = null;11};12goog.inherits(com.ttProject.frame.h264.type.SliceIDR, com.ttProject.frame.h264.SliceFrame);13com.ttProject.frame.h264.type.SliceIDR.prototype.load = function(channel, callback) {14 var _this = this;15 // bufferの中身を保持しておく。16 channel.read(channel.size() - channel.position(), function(data) {17 _this._buffer = data;18 callback();19 });20};21com.ttProject.frame.h264.type.SliceIDR.prototype.getData = function() {22 return com.ttProject.util.ArrayUtil.connect(23 this.getTypeBuffer(),24 this.getSliceHeaderBuffer(),25 this._buffer26 );...

Full Screen

Full Screen

slice.js

Source:slice.js Github

copy

Full Screen

1goog.provide("com.ttProject.frame.h264.type.Slice");2goog.require("com.ttProject.frame.h264.SliceFrame");3goog.require("com.ttProject.util.ArrayUtil");4/**5 * @constructor6 */7com.ttProject.frame.h264.type.Slice = function(forbiddenZeroBit, nalRefIdc, type) {8 goog.base(this, forbiddenZeroBit, nalRefIdc, type);9 this._buffer = null;10};11goog.inherits(com.ttProject.frame.h264.type.Slice, com.ttProject.frame.h264.SliceFrame);12com.ttProject.frame.h264.type.Slice.prototype.load = function(channel, callback) {13 var _this = this;14 channel.read(channel.size() - channel.position(), function(data) {15 _this._buffer = data;16 callback();17 });18};19com.ttProject.frame.h264.type.Slice.prototype.getData = function() {20 return com.ttProject.util.ArrayUtil.connect(21 this.getTypeBuffer(),22 this.getSliceHeaderBuffer(),23 this._buffer24 );...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('getBySel', (selector, ...args) => {2 return cy.get(`[data-test=${selector}]`, ...args)3})4Cypress.Commands.add('getBySelLike', (selector, ...args) => {5 return cy.get(`[data-test*=${selector}]`, ...args)6})7Cypress.Commands.add('getBySelLike', (selector, ...args) => {8 return cy.get(`[data-test*=${selector}]`, ...args)9})10Cypress.Commands.add('getBySelLike', (selector, ...args) => {11 return cy.get(`[data-test*=${selector}]`, ...args)12})13Cypress.Commands.add('getBySelLike', (selector, ...args) => {14 return cy.get(`[data-test*=${selector}]`, ...args)15})16Cypress.Commands.add('getBySelLike', (selector, ...args) => {17 return cy.get(`[data-test*=${selector}]`, ...args)18})19Cypress.Commands.add('getBySelLike', (selector, ...args) => {20 return cy.get(`[data-test*=${selector}]`, ...args)21})22Cypress.Commands.add('getBySelLike', (selector, ...args) => {23 return cy.get(`[data-test*=${selector}]`, ...args)24})25Cypress.Commands.add('getBySelLike', (selector, ...args) => {26 return cy.get(`[data-test*=${selector}]

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2 it('should check the type of the element', () => {3 cy.get('h1').should('have.text', 'Kitchen Sink')4 cy.get('h1').should('have.class', 'title')5 cy.get('h1').should('have.id', 'main-title')6 cy.get('h1').should('have.attr', 'data-test')7 cy.get('h1').should('have.css', 'color')8 cy.get('h1').should('have.css', 'font-family')9 cy.get('h1').should('have.css', 'font-size')10 cy.get('h1').should('have.css', 'font-weight')11 cy.get('h1').should('have.css', 'line-height')12 cy.get('h1').should('have.css', 'text-transform')13 cy.get('h1').should('have.css', 'text-align')14 cy.get('h1').should('have.css', 'margin')15 cy.get('h1').should('have.css', 'padding')16 cy.get('h1').should('have.css', 'box-sizing')17 cy.get('h1').should('have.css', 'display')18 cy.get('h1').should('have.css', 'position')19 cy.get('h1').should('have.css', 'top')20 cy.get('h1').should('have.css', 'left')21 cy.get('h1').should('have.css', 'right')22 cy.get('h1').should('have.css', 'bottom')23 cy.get('h1').should('have.css', 'z-index')24 cy.get('h1').should('have.css', 'width')25 cy.get('h1').should('have.css', 'height')26 cy.get('h1').should('have.css', 'min-width')27 cy.get('h1').should('have.css', 'max-width')28 cy.get('h1').should('have.css', 'min-height')29 cy.get('h1').should('have.css', 'max-height')30 cy.get('h1').should('have.css', 'background-color')31 cy.get('h1').should('have.css', 'background-image')32 cy.get('h1').should

Full Screen

Using AI Code Generation

copy

Full Screen

1it('should have a type.slice method', () => {2 cy.get('input').type('hello world').then(($input) => {3 expect($input).to.have.property('slice')4 })5})6it('should have a type.slice method', () => {7 cy.get('input').type('hello world').then(($input) => {8 expect($input).to.have.property('slice')9 })10})11it('should have a type.slice method', () => {12 cy.get('input').type('hello world').then(($input) => {13 expect($input).to.have.property('slice')14 })15})16it('should have a type.slice method', () => {17 cy.get('input').type('hello world').then(($input) => {18 expect($input).to.have.property('slice')19 })20})21it('should have a type.slice method', () => {22 cy.get('input').type('hello world').then(($input) => {23 expect($input).to.have.property('slice')24 })25})26it('should have a type.slice method', () => {27 cy.get('input').type('hello world').then(($input) => {28 expect($input).to.have.property('slice')29 })30})31it('should have a type.slice method', () => {32 cy.get('input').type('hello world').then(($input) => {33 expect($input

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', () => {2 it('Does not do much!', () => {3 expect(true).to.equal(true)4 })5})6describe('My Second Test', () => {7 it('Visits the Kitchen Sink', () => {8 cy.contains('type').click()9 cy.url().should('include', '/commands/actions')10 cy.get('.action-email')11 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Get the type of the element', () => {2 it('Get the type of the element', () => {3 cy.get('.home-list > :nth-child(1) > a').then(($el) => {4 console.log(type)5 console.log(type.slice(0, 5))6 console.log(type.slice(7))7 console.log(type.slice(0, -1))8 console.log(type.slice(-1))9 console.log(type.slice(0, -2))10 console.log(type.slice(-2))11 })12 })13})14describe('Get the type of the element', () => {15 it('Get the type of the element', () => {16 cy.get('.home-list > :nth-child(1) > a').then(($el) => {17 console.log(type)18 console.log(type.substring(0, 5))19 console.log(type.substring(7))20 })21 })22})23describe('Get the type of the element', () => {24 it('Get the type of the element', () => {25 cy.get('.home-list > :nth-child(1) > a

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress 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