How to use alternatives method in Jest

Best JavaScript code snippet using jest

Alternatives.jsx

Source:Alternatives.jsx Github

copy

Full Screen

1import React from 'react';2import MaterialIcon from 'react-google-material-icons';3import {4  busResults,5  trainResults,6  motorbikeResults,7  walkResults,8  bikeResults,9  planeResults,10} from '../getResults/getResults';11import treeIcon from './img/saveco2-tree-icon.svg';12import './alternatives.css';13export const getAlternativeObject = ({ userData, journeyDistance }) => {14  let alternativeTransport = [];15  console.log(userData);16  // const editedUserData = { ...userData, peopleCount: parseInt(peopleCount) };17  if (userData.transportType === 'car') {18    alternativeTransport = getCarAlternatives(userData, journeyDistance);19  }20  if (userData.transportType === 'motorbike') {21    alternativeTransport = getMotorbikeAlternatives(userData, journeyDistance);22  }23  if (userData.transportType === 'bus') {24    alternativeTransport = getBusAlternatives(userData, journeyDistance);25  }26  if (userData.transportType === 'train') {27    alternativeTransport = getTrainAlternatives(userData, journeyDistance);28  }29  if (userData.transportType === 'subway') {30    alternativeTransport = getSubwayAlternatives(userData, journeyDistance);31  }32  if (userData.transportType === 'plane') {33    alternativeTransport = getPlaneAlternatives(userData, journeyDistance);34  }35  if (userData.transportType === 'ferry') {36    alternativeTransport = getFerryAlternatives(userData, journeyDistance);37  }38  return alternativeTransport;39};40export const Alternatives = ({ alternativeTransport, userData }) => {41  console.log(userData);42  return (43    <>44      <GetChoices userData={userData} />45      {alternativeTransport.map((transport, index) => {46        console.log(transport);47        return (48          <React.Fragment key={index}>49            <div className="results__alternative-transport">50              <div className="alternative-transport__container">51                <MaterialIcon icon={transport.icon} size={48}></MaterialIcon>52                <div className="alternative-transport__container-phrase">53                  <h4>{transport.text}</h4>54                  <div className="transport__graph--container">55                    <div56                      className="transport__graph"57                      style={{58                        width: `${transport.result.emmissionsShare * 100}%`,59                      }}60                    />61                  </div>62                </div>63              </div>64              <div className="alternative-transport__details">65                <p>66                  {transport.result.emmissions} kg CO<sub>2</sub>67                </p>68                <div className="alternative-transport__details-tree">69                  <p>{transport.result.tree}</p>70                  <img71                    className="material-icons__tree"72                    src={treeIcon}73                    alt="tree"74                  />75                </div>76              </div>77            </div>78          </React.Fragment>79        );80      })}81      <GetOtherAlternatives userData={userData} />82      <GetTreeAlternatives userData={userData} />83    </>84  );85};86export const getCarAlternatives = (87  { distance, peopleCount, fuel },88  journeyDistance,89) => {90  const alternatives = [];91  const alternativeResults = getAlternativeResults({92    journeyDistance,93    peopleCount,94    fuel,95    distance,96  });97  if (98    peopleCount === 1 &&99    (fuel === 'diesel' ||100      fuel === 'petrol' ||101      fuel === 'hybrid' ||102      fuel === 'CNG' ||103      fuel === 'LPG' ||104      fuel === 'other')105  ) {106    if (distance <= 10) {107      alternatives.push(alternativeResults.walk);108      alternatives.push(alternativeResults.bike);109    } else if (distance <= 100) {110      alternatives.push(alternativeResults.bike);111      alternatives.push(alternativeResults.train);112      alternatives.push(alternativeResults.bus);113      alternatives.push(alternativeResults.motorbike);114    } else if (distance <= 200) {115      alternatives.push(alternativeResults.train);116      alternatives.push(alternativeResults.bus);117      alternatives.push(alternativeResults.motorbike);118    } else {119      alternatives.push(alternativeResults.train);120      alternatives.push(alternativeResults.bus);121    }122  }123  if (124    peopleCount === 2 &&125    (fuel === 'diesel' ||126      fuel === 'petrol' ||127      fuel === 'hybrid' ||128      fuel === 'CNG' ||129      fuel === 'LPG' ||130      fuel === 'other')131  ) {132    if (distance <= 10) {133      alternatives.push(alternativeResults.walk);134      alternatives.push(alternativeResults.bike);135    } else if (distance <= 100) {136      alternatives.push(alternativeResults.bike);137      alternatives.push(alternativeResults.train);138      alternatives.push(alternativeResults.motorbike);139    } else if (distance <= 200) {140      alternatives.push(alternativeResults.train);141      alternatives.push(alternativeResults.motorbike);142    } else {143      alternatives.push(alternativeResults.train);144    }145  }146  if (147    (peopleCount === 3 || peopleCount === 4) &&148    (fuel === 'diesel' ||149      fuel === 'petrol' ||150      fuel === 'CNG' ||151      fuel === 'other')152  ) {153    if (distance <= 10) {154      alternatives.push(alternativeResults.walk);155      alternatives.push(alternativeResults.bike);156    } else if (distance <= 100) {157      alternatives.push(alternativeResults.bike);158      alternatives.push(alternativeResults.train);159    } else {160      alternatives.push(alternativeResults.train);161    }162  }163  if (peopleCount >= 3 && peopleCount <= 5 && fuel === 'LPG') {164    if (distance <= 10) {165      alternatives.push(alternativeResults.walk);166      alternatives.push(alternativeResults.bike);167    } else if (distance <= 100) {168      alternatives.push(alternativeResults.bike);169      alternatives.push(alternativeResults.train);170    } else {171      alternatives.push(alternativeResults.train);172    }173  }174  if (peopleCount === 3 && fuel === 'hybrid') {175    if (distance <= 10) {176      alternatives.push(alternativeResults.walk);177      alternatives.push(alternativeResults.bike);178    } else if (distance <= 100) {179      alternatives.push(alternativeResults.bike);180      alternatives.push(alternativeResults.train);181    } else {182      alternatives.push(alternativeResults.train);183    }184  }185  if (186    peopleCount >= 5 &&187    peopleCount <= 9 &&188    (fuel === 'diesel' ||189      fuel === 'petrol' ||190      fuel === 'CNG' ||191      fuel === 'other')192  ) {193    if (distance <= 10) {194      alternatives.push(alternativeResults.walk);195      alternatives.push(alternativeResults.bike);196    } else if (distance <= 100) {197      alternatives.push(alternativeResults.bike);198    }199  }200  if (peopleCount >= 4 && peopleCount <= 6 && fuel === 'hybrid') {201    if (distance <= 10) {202      alternatives.push(alternativeResults.walk);203      alternatives.push(alternativeResults.bike);204    } else if (distance <= 100) {205      alternatives.push(alternativeResults.bike);206    }207  }208  if (peopleCount >= 6 && peopleCount <= 9 && fuel === 'LPG') {209    if (distance <= 10) {210      alternatives.push(alternativeResults.walk);211      alternatives.push(alternativeResults.bike);212    } else if (distance <= 100) {213      alternatives.push(alternativeResults.bike);214    }215  }216  if (217    (peopleCount >= 3 && peopleCount <= 5 && fuel === 'plugInHybrid') ||218    (peopleCount === 2 && fuel === 'electro')219  ) {220    if (distance <= 10) {221      alternatives.push(alternativeResults.walk);222      alternatives.push(alternativeResults.bike);223    } else if (distance <= 100) {224      alternatives.push(alternativeResults.bike);225    }226  }227  if (228    ((peopleCount === 1 || peopleCount === 2) && fuel === 'plugInHybrid') ||229    (peopleCount === 1 && fuel === 'electro')230  ) {231    if (distance <= 10) {232      alternatives.push(alternativeResults.walk);233      alternatives.push(alternativeResults.bike);234    } else if (distance <= 100) {235      alternatives.push(alternativeResults.bike);236      alternatives.push(alternativeResults.train);237    } else {238      alternatives.push(alternativeResults.train);239    }240  }241  if (242    (peopleCount >= 3 && peopleCount <= 6 && fuel === 'electro') ||243    (peopleCount >= 6 && peopleCount <= 9 && fuel === 'plugInHybrid') ||244    (peopleCount >= 7 && peopleCount <= 9 && fuel === 'hybrid')245  ) {246    if (distance <= 10) {247      alternatives.push(alternativeResults.walk);248    }249  }250  return alternatives;251};252export const getMotorbikeAlternatives = (253  { distance, peopleCount },254  journeyDistance,255) => {256  const alternatives = [];257  const alternativeResults = getAlternativeResults({258    journeyDistance,259    peopleCount,260    distance,261  });262  if (peopleCount === 1) {263    if (distance <= 10) {264      alternatives.push(alternativeResults.walk);265      alternatives.push(alternativeResults.bike);266    } else if (distance <= 100) {267      alternatives.push(alternativeResults.bike);268      alternatives.push(alternativeResults.train);269      alternatives.push(alternativeResults.bus);270    } else {271      alternatives.push(alternativeResults.train);272      alternatives.push(alternativeResults.bus);273    }274  }275  if (peopleCount === 2) {276    if (distance <= 10) {277      alternatives.push(alternativeResults.walk);278      alternatives.push(alternativeResults.bike);279    } else if (distance <= 100) {280      alternatives.push(alternativeResults.bike);281      alternatives.push(alternativeResults.train);282    } else {283      alternatives.push(alternativeResults.train);284    }285  }286  return alternatives;287};288export const getBusAlternatives = ({ distance }, journeyDistance) => {289  const alternatives = [];290  const alternativeResults = getAlternativeResults({291    journeyDistance,292    distance,293  });294  if (distance <= 10) {295    alternatives.push(alternativeResults.walk);296    alternatives.push(alternativeResults.bike);297  } else if (distance <= 100) {298    alternatives.push(alternativeResults.bike);299    alternatives.push(alternativeResults.train);300  } else {301    alternatives.push(alternativeResults.train);302  }303  return alternatives;304};305export const getTrainAlternatives = ({ distance }, journeyDistance) => {306  const alternatives = [];307  const alternativeResults = getAlternativeResults({308    journeyDistance,309    distance,310  });311  if (distance <= 10) {312    alternatives.push(alternativeResults.walk);313    alternatives.push(alternativeResults.bike);314  } else if (distance <= 100) {315    alternatives.push(alternativeResults.bike);316  }317  return alternatives;318};319export const getSubwayAlternatives = ({ distance }, journeyDistance) => {320  const alternatives = [];321  const alternativeResults = getAlternativeResults({322    journeyDistance,323    distance,324  });325  if (distance <= 10) {326    alternatives.push(alternativeResults.walk);327    alternatives.push(alternativeResults.bike);328  } else if (distance <= 100) {329    alternatives.push(alternativeResults.bike);330  }331  return alternatives;332};333export const getPlaneAlternatives = ({ distance }, journeyDistance) => {334  const alternatives = [];335  const alternativeResults = getAlternativeResults({336    journeyDistance,337    distance,338  });339  alternatives.push(alternativeResults.trainPlane);340  return alternatives;341};342export const getFerryAlternatives = ({ distance }, journeyDistance) => {343  const alternatives = [];344  const alternativeResults = getAlternativeResults({345    journeyDistance,346    distance,347  });348  alternatives.push(alternativeResults.plane);349  return alternatives;350};351const getAlternativeResults = ({ journeyDistance, peopleCount }) => {352  return {353    walk: {354      text: 'Máme lepší nápad! Pohyb na čerstvém vzduchu je zdravý.',355      icon: 'directions_walk',356      result: walkResults({ journeyDistance }),357    },358    bike: {359      text: 'Co takhle šlápnout do pedálů?',360      icon: 'pedal_bike',361      result: bikeResults({ journeyDistance }),362    },363    train: {364      text: 'Vlak je lepší volba. Alespoň během cesty vyřídíš maily.',365      icon: 'train',366      result: trainResults({ journeyDistance }),367    },368    trainPlane: {369      text: 'Zjisti si na nádraží, jestli ti nejede vlak. Třeba se Matýsek tentokrát nepo...',370      icon: 'train',371      result: trainResults({ journeyDistance }),372    },373    bus: {374      text: 'Možná ti jede autobus. Zkontroluj jízdní řády!',375      icon: 'directions_bus',376      result: busResults({ journeyDistance }),377    },378    motorbike: {379      text: 'Máš doma motorku? Tak ji vyvez!',380      icon: 'two_wheeler',381      result: motorbikeResults({ journeyDistance, peopleCount }),382    },383    plane: {384      text: 'Sedni na letadlo! Budeš tam rychleji a možná nenarazíš na ledovec.',385      icon: 'flight',386      result: planeResults({ journeyDistance }),387    },388  };389};390export const GetOtherAlternatives = ({391  userData: { distance, peopleCount, transportType, fuel },392}) => {393  if (transportType === 'car' && peopleCount <= 2) {394    return (395      <>396        <div className="alternative--others">397          <MaterialIcon icon={'person_add'} size={48}></MaterialIcon>398          <h4>399            {' '}400            Co třeba někoho svézt (nebo svést)? Ve&nbsp;více lidech se lépe401            jede.402          </h4>403        </div>404      </>405    );406  }407  if (transportType === 'ferry') {408    return (409      <>410        <div className="alternative--others">411          <MaterialIcon icon={'pool'} size={48}></MaterialIcon>412          <h4>To snad přeplaveš, ne?</h4>413        </div>414      </>415    );416  }417  if (418    (transportType === 'car' &&419      fuel === 'electro' &&420      peopleCount >= 7 &&421      peopleCount <= 9) ||422    (transportType === 'train' && distance > 100) ||423    transportType === 'bike' ||424    transportType === 'walk'425  ) {426    return (427      <>428        <div className="alternative--others">429          <MaterialIcon icon={'star_rate'} size={48}></MaterialIcon>430          <h4>Děkujeme, že pomáháš chránit životní prostředí. </h4>431        </div>432      </>433    );434  }435  return null;436};437export const GetTreeAlternatives = ({ userData: { transportType, fuel } }) => {438  if (439    transportType === 'car' ||440    transportType === 'subway' ||441    transportType === 'motorbike' ||442    transportType === 'bus' ||443    transportType === 'plane' ||444    transportType === 'ferry'445  ) {446    return (447      <>448        <div className="alternative--others">449          <MaterialIcon icon={'park'} size={48}></MaterialIcon>450          <h4>451            Víš, že se můžeš zapojit do sázení stromů? Vyber si kde na&nbsp;452            <a href="https://www.sazimebudoucnost.cz/">Sázíme budoucnost</a>.453          </h4>454        </div>455      </>456    );457  }458  return null;459};460export const GetChoices = ({461  userData: { distance, peopleCount, fuel, transportType },462}) => {463  let getChoicesText = '';464  if (465    (distance > 100 &&466      ((transportType === 'car' &&467        peopleCount >= 5 &&468        peopleCount <= 9 &&469        (fuel === 'diesel' ||470          fuel === 'petrol' ||471          fuel === 'CNG' ||472          fuel === 'other')) ||473        (peopleCount >= 4 && peopleCount <= 6 && fuel === 'hybrid') ||474        (peopleCount >= 6 && peopleCount <= 9 && fuel === 'LPG') ||475        (peopleCount >= 3 && peopleCount <= 5 && fuel === 'plugInHybrid'))) ||476    (distance > 100 && transportType === 'subway')477  ) {478    getChoicesText = <>Lepší volba nás nenapadá, i&nbsp;když…</>;479  } else if (480    (distance > 10 &&481      transportType === 'car' &&482      fuel === 'electro' &&483      peopleCount >= 3 &&484      peopleCount <= 6) ||485    (distance > 10 &&486      fuel === 'plugInHybrid' &&487      peopleCount >= 6 &&488      peopleCount <= 9) ||489    (distance > 10 && fuel === 'hybrid' && peopleCount >= 7 && peopleCount <= 9)490  ) {491    getChoicesText = <>Lepší volba nás nenapadá, i&nbsp;když…</>;492  } else if (493    (fuel === 'electro' && peopleCount >= 7 && peopleCount <= 9) ||494    (transportType === 'train' && distance > 100) ||495    transportType === 'bike' ||496    transportType === 'walk'497  ) {498    getChoicesText = <>Skvělá volba!</>;499  } else {500    getChoicesText = (501      <>502        Jsi si svojí volbou jistý? <br /> Zkus raději jednu z&nbsp;alternativ!503      </>504    );505  }506  return <h3 className="results__alternatives--choice">{getChoicesText}</h3>;...

Full Screen

Full Screen

properties-test.js

Source:properties-test.js Github

copy

Full Screen

1module("Text Descendant", {2});3test("Find text descendants in an iframe.", function() {4    // Setup fixture5    var fixture = document.getElementById('qunit-fixture');6    var iframe = document.createElement('iframe');7    var html = '<body><div id="foo">bar</div></body>';8    fixture.appendChild(iframe);9    iframe.contentWindow.document.open();10    iframe.contentWindow.document.write(html);11    iframe.contentWindow.document.close();12    var foo = iframe.contentDocument.getElementById("foo");13    equal(axs.properties.hasDirectTextDescendant(foo), true);14});15test("Find text descendants in a <template>.", function() {16    var templ = document.createElement('template');17    templ.innerHTML = '<div>bar</div>';18    // <template> might not be supported by the browser, test anyway.19    var foo = (templ.content || templ).firstChild;20    equal(axs.properties.hasDirectTextDescendant(foo), true);21});22module('findTextAlternatives', {23    setup: function () {24        this.fixture_ = document.getElementById('qunit-fixture');25    }26});27test('returns the calculated text alternative for the given element', function() {28    var targetNode = document.createElement('select');29    this.fixture_.appendChild(targetNode);30    try {31        equal(axs.properties.findTextAlternatives(targetNode, {}, true), '');32    } catch(e) {33        ok(false, 'Threw exception');34    }35});36test('Image with no text alternative', function() {37    var fixture = document.getElementById('qunit-fixture');38    var img = fixture.appendChild(document.createElement('img'));39    img.src = 'smile.jpg';40    var textAlternatives = {};41    axs.properties.findTextAlternatives(img, textAlternatives);42    equal(Object.keys(textAlternatives).length, 0, 'Image has no text alternative');43});44test('Image with alt text', function() {45    var fixture = document.getElementById('qunit-fixture');46    var img = fixture.appendChild(document.createElement('img'));47    img.src = 'smile.jpg';48    img.alt = 'Smile!';49    var textAlternatives = {};50    axs.properties.findTextAlternatives(img, textAlternatives);51    equal(Object.keys(textAlternatives).length, 1, 'exactly one text alternative');52    equal('alt' in textAlternatives, true, 'alt in textAlternatives');53    equal('Smile!', textAlternatives.alt.text);54});55test('Input type image with alt text', function() {56    var fixture = document.getElementById('qunit-fixture');57    var img = fixture.appendChild(document.createElement('input'));58    img.type = "image";59    img.src = 'smile.jpg';60    img.alt = 'Smile!';61    var textAlternatives = {};62    axs.properties.findTextAlternatives(img, textAlternatives);63    equal(Object.keys(textAlternatives).length, 1, 'exactly one text alternative');64    equal('alt' in textAlternatives, true, 'alt in textAlternatives');65    equal('Smile!', textAlternatives.alt.text);66});67test('Image with aria label', function() {68    var fixture = document.getElementById('qunit-fixture');69    var img = fixture.appendChild(document.createElement('img'));70    img.src = 'smile.jpg';71    img.setAttribute('aria-label', 'Smile!');72    var textAlternatives = {};73    axs.properties.findTextAlternatives(img, textAlternatives);74    equal(Object.keys(textAlternatives).length, 1, 'exactly one text alternative');75    equal('ariaLabel' in textAlternatives, true, 'ariaLabel in textAlternatives');76    equal('Smile!', textAlternatives.ariaLabel.text);77});78test('Image with aria labelledby', function() {79    var fixture = document.getElementById('qunit-fixture');80    var img = fixture.appendChild(document.createElement('img'));81    img.src = 'smile.jpg';82    var label = fixture.appendChild(document.createElement('div'));83    label.textContent = 'Smile!';84    label.id = 'label';85    img.setAttribute('aria-labelledby', 'label');86    var textAlternatives = {};87    axs.properties.findTextAlternatives(img, textAlternatives);88    equal(Object.keys(textAlternatives).length, 1, 'exactly one text alternative');89    equal('ariaLabelledby' in textAlternatives, true, 'ariaLabelledby in textAlternatives');90    equal('Smile!', textAlternatives.ariaLabelledby.text);91});92test('Image with title', function() {93    var fixture = document.getElementById('qunit-fixture');94    var img = fixture.appendChild(document.createElement('img'));95    img.src = 'smile.jpg';96    img.setAttribute('title', 'Smile!');97    var textAlternatives = {};98    axs.properties.findTextAlternatives(img, textAlternatives);99    equal(Object.keys(textAlternatives).length, 1, 'exactly one text alternative');100    equal('title' in textAlternatives, true, 'title in textAlternatives');101    equal('Smile!', textAlternatives.title.text);102});103test('Link with aria-hidden text', function() {104    var fixture = document.getElementById('qunit-fixture');105    var anchor = fixture.appendChild(document.createElement('a'));106    anchor.href = '#';107    anchor.innerHTML = '<span aria-hidden="true">X</span><span>Close this window</span>';108    var textAlternatives = {};109    var result = axs.properties.findTextAlternatives(anchor, textAlternatives);110    equal(Object.keys(textAlternatives).length, 1, 'exactly one text alternative');111    equal('content' in textAlternatives, true, 'content in textAlternatives');112    equal(textAlternatives.content.text, 'Close this window');113    equal(result, 'Close this window');114});115test('Link with aria-labelledby aria-hidden text', function() {116    var fixture = document.getElementById('qunit-fixture');117    var anchor = fixture.appendChild(document.createElement('a'));118    anchor.href = '#';119    anchor.setAttribute('aria-labelledby', 'foobar');120    anchor.innerHTML = '<span id="foobar" aria-hidden="true">X</span><span>Close this window</span>';121    var textAlternatives = {};122    var result = axs.properties.findTextAlternatives(anchor, textAlternatives);123    equal(Object.keys(textAlternatives).length, 2, 'exactly two text alternatives');124    equal('ariaLabelledby' in textAlternatives, true, 'ariaLabelledby in textAlternatives');125    equal(textAlternatives.content.text, 'Close this window');126    equal(textAlternatives.ariaLabelledby.text, 'X');127    equal(result, 'X');128});129test('Link with aria-labelledby element with aria-label', function() {130    var fixture = document.getElementById('qunit-fixture');131    var anchor = fixture.appendChild(document.createElement('a'));132    anchor.href = '#';133    anchor.setAttribute('aria-labelledby', 'foobar');134    var label = fixture.appendChild(document.createElement('span'));135    label.setAttribute('id', 'foobar');136    label.setAttribute('aria-label', 'Learn more about trout fishing');137    var textAlternatives = {};138    var result = axs.properties.findTextAlternatives(anchor, textAlternatives);139    equal(Object.keys(textAlternatives).length, 1, 'exactly one text alternative');140    equal('ariaLabelledby' in textAlternatives, true, 'ariaLabelledby in textAlternatives');141    equal(textAlternatives.ariaLabelledby.text, 'Learn more about trout fishing');142    equal(result, 'Learn more about trout fishing');143});144module('getTextFromHostLanguageAttributes', {145    setup: function () {146        this.fixture_ = document.getElementById('qunit-fixture');147    }148});149test('does not crash when targetNode has a numeric id attribute', function() {150    var targetNode = document.createElement('input');151    targetNode.setAttribute('id', '123_user');152    this.fixture_.appendChild(targetNode);153    try {154        equal(axs.properties.getTextFromHostLanguageAttributes(targetNode, {}, null), null);155    } catch(e) {156        ok(false, 'Threw exception: ' + e);157    }158});159module('getFocusProperties', {});160test('Get focus properties', function() {161    // Setup fixture162    var fixture = document.getElementById('qunit-fixture');163    fixture.style.top = 0;164    fixture.style.left = 0;165    var html = '<div id="overlapped" tabindex="0">Overlapped element</div>' +166               '<div id="overlapping" style="font-size: 48px; ' +167               'position: relative; top: -40px; height: 40px; ' +168               'background: rgba(255, 255, 255, 0.5);">Overlapping div</div>';169    fixture.innerHTML = html;170    var overlapped = document.getElementById('overlapped');171    var overlapping = document.getElementById('overlapping');172    var rect = overlapped.getBoundingClientRect();173    var center_x = (rect.left + rect.right) / 2;174    var center_y = (rect.top + rect.bottom) / 2;175    var elementAtPoint = document.elementFromPoint(center_x, center_y);176    var focusProperties = axs.properties.getFocusProperties(overlapped);177    if (elementAtPoint != null) {178        deepEqual(focusProperties,179                  { tabindex: { value: "0", valid: true },180                    visible: { value: false,181                               hidden: {182                                   value: false,183                                   valid: false184                               },185                               valid: false,186                               overlappingElements: [overlapping] } });187    } else {188        // This will occur if running in phantomjs.189        deepEqual(focusProperties,190                  { tabindex: { value: "0", valid: true },191                    visible: { value: true, valid: true } });192    }193});194module("getTextFromDescendantContent", {195    setup: function () {196        this.fixture_ = document.getElementById('qunit-fixture');197    }198});199test("returns text from the descendants of the element", function() {200    var html = '<label>\n' +201            '  <input type="radio" id="reason_Screenshot" name="reason" value="screenshot"></input>\n' +202            '</label>';203    this.fixture_.innerHTML = html;204    var targetNode = this.fixture_.querySelector('label');205    try {206        equal(axs.properties.getTextFromDescendantContent(targetNode), '');207        return ok(true);208    } catch(e) {209        return ok(false, 'Threw exception: ' + e);210    }211});212module('getImplicitRole', {213    setup: function() {}214});215test('get implicit role for button', function() {216    var element = document.createElement('button');217    var actual = axs.properties.getImplicitRole(element);218    equal(actual, 'button');219});220test('get implicit role for input type=button', function() {221    var element = document.createElement('input');222    element.setAttribute('type', 'button');223    var actual = axs.properties.getImplicitRole(element);224    equal(actual, 'button');225});226test('get implicit role for input type=range', function() {227    var element = document.createElement('input');228    element.setAttribute('type', 'range');229    var actual = axs.properties.getImplicitRole(element);230    equal(actual, 'slider');231});232test('get implicit role for li out of context', function() {233    var element = document.createElement('li');234    var actual = axs.properties.getImplicitRole(element);235    strictEqual(actual, '');236});237test('get implicit role for li child of ul', function() {238    var element = document.createElement('ul');239    element = element.appendChild(document.createElement('li'));240    var actual = axs.properties.getImplicitRole(element);241    equal(actual, 'listitem');242});243test('get implicit role for li descendant of ul', function() {244    var element = document.createElement('ul');245    element = element.appendChild(document.createElement('div'));  // bad html i know but good for test246    element = element.appendChild(document.createElement('li'));247    var actual = axs.properties.getImplicitRole(element);248    strictEqual(actual, '');249});250module('getTextProperties', {});251test('Image with no text alternative', function() {252    var fixture = document.getElementById('qunit-fixture');253    var img = fixture.appendChild(document.createElement('img'));254    img.src = 'smile.jpg';255    var textProperties = axs.properties.getTextProperties(img);256    equal('alt' in textProperties, true, 'alt in textProperties');257    equal(textProperties.alt.valid, false, 'alt is not valid');258    equal('filename' in textProperties, true, 'filename in textProperties');259    equal(textProperties.filename.text, 'smile.jpg');260    equal('computedText' in textProperties, true, 'computedText in textProperties');261    equal(textProperties.computedText, 'smile.jpg');...

Full Screen

Full Screen

AddQuestion.js

Source:AddQuestion.js Github

copy

Full Screen

1import React, { Component } from 'react';2import { Alert } from 'reactstrap';3import translate from '../../../i18n/translate';4import { FormattedMessage } from 'react-intl';5import TextareaAutosize from 'react-textarea-autosize';6class AddQuestion extends Component {7    constructor(){8        super();9        10        this.state = {11            description: "",12            type: 0,13            alternatives: [],14            errors: null,15            toggleAlert: false16        };17        this.onToggleAlert.bind(this);18        this.onChange.bind(this);19        this.onChangeType.bind(this);20        this.renderSwitch.bind(this);21        this.isFormValid.bind(this);22        this.onQuestionSubmit.bind(this);23    }24    onToggleAlert = () => {25        this.setState({ errors: null, toggleAlert: false });26    }27    28    onChange = (e) => {29        this.setState({ [e.target.name]: e.target.value });30    }31    clearErrors = () => {32        this.setState({ errors: null });33    }34    onAlternativeChange = (index, e) => {35        let alternatives = this.state.alternatives;36        37        let current_alternative = alternatives[index];38        let updated = { ...current_alternative, description: e.target.value };39        let updatedAlternatives = [40            ...alternatives.slice(0, index),41            updated,42            ...alternatives.slice(index + 1),43          ];44        45        this.setState({ alternatives: updatedAlternatives });46    }47    onMarkCorrect = (index, e) => {48        let { alternatives, type } = this.state;49        let updatedAlternatives = [];50        if(type === 1 || type === 2)51            updatedAlternatives = alternatives.map((alt, i) => i === index ? { ...alt, correct: true } : { ...alt, correct: false });52        else {53            let current_alternative = alternatives[index];54            let updated = { ...current_alternative, correct: !current_alternative.correct };55            updatedAlternatives = [56                ...alternatives.slice(0, index),57                updated,58                ...alternatives.slice(index + 1),59              ];60        }61        62        this.setState({ alternatives: updatedAlternatives });63    }64    onChangeType = (e) => {65        let type = parseInt(e.target.value);66        let alternatives = [];67        68        if(type === 1)69            alternatives = [ {description: "Yes", correct: false}, {description: "No", correct: false} ];70        else71            alternatives = [ {description: "", correct: false}, {description: "", correct: false}, {description: "", correct: false}, {description: "", correct: false} ];72        73        this.setState({ type, alternatives });74    }75    isFormValid = () => {76        const { description, type, alternatives } = this.state;77        if(description === "") {78            this.setState({ errors: translate('description-required'), toggleAlert: true });79            return false;80        }81        82        else if(type === 0) {83            this.setState({ errors: translate('alternatives-required'), toggleAlert: true });84            return false;85        }86        let correct = 0;87        let count = alternatives.length;88        for(let i = 0; i < count; i++ ) {89            if(alternatives[i].description === "") {90                this.setState({ errors: translate('alternatives-blank'), toggleAlert: true });91                return false92            }93            if(alternatives[i].correct)94                correct++;95        }96        if((type === 1 && correct !== 1) || (type === 2 && correct !== 1)) {97            this.setState({ errors: translate('one-correct-answer-required'), toggleAlert: true });98            return false;99        }100        if(type === 3 && correct !== 2) {101            this.setState({ errors: translate('two-correct-answers-required'), toggleAlert: true });102            return false;103        }104        return true;105    }106    onQuestionSubmit = () => {107        // e.preventDefault();108        // Validation109        let valid = this.isFormValid();110        if(valid) {111            const { description, type, alternatives } = this.state;112            const newQuestion = { description, type, alternatives };113            114            this.props.addQuestion(newQuestion);115        }116    }117    renderSwitch = (alternatives) => {118        switch(alternatives.length) {119          case 2:120            return (121                <>122                    {123                        alternatives.map((alt, index) => {124                            return (125                                <div key={index} className="form-group col-md-6 my-2">126                                    <div className="form-check text-center">127                                        <input id={index} name={index} type="radio"128                                             className="form-check-input shadow-sm"  129                                             onChange={this.onMarkCorrect.bind(this, index)} checked={alt.correct}/>130                                        <label className="form-check-label" htmlFor={index}>131                                            {alt.description}132                                        </label>133                                    </div>134                                </div>135                            )136                        })137                    }138                </>139            );140          default:141              return (142                <div className="row" id="alternatives">143                    {144                        alternatives.map((alt, index) => {145                            return (146                                <div key={index} className="form-group col-md-3 my-2">147                                    <div className="form-check">148                                    <input id={index} name={index} type="checkbox"149                                        className="form-check-input shadow-sm" 150                                        onChange={this.onMarkCorrect.bind(this, index)} checked={alt.correct}/>151                                    <input id="description" name="description"152                                        className="form-control form-control-sm shadow-sm"153                                        value={alt.description} onChange={this.onAlternativeChange.bind(this, index)}/>154                                    </div>155                                </div>156                            )157                        })158                    }159                </div>160            );161        };162    }163    render() {164        const { description, type, alternatives, errors, toggleAlert } = this.state;165        return (166            <div className="col-md-12 my-2 p-4 border rounded shadow">167                <div>168                    <div className="form-row" id="questionForm">169                        <div className="form-group col-md-12">170                            <label htmlFor="description"> {translate('description')} </label>171                            <TextareaAutosize minRows="3" id="description" name="description"172                                className="form-control form-control-sm shadow-sm"173                                value={description} onChange={this.onChange}/>174                        </div>175                        <div className="form-group col-md-12">176                            <label htmlFor="type"> {translate('type')} </label>177                            <select id="type" name="type" className="form-control form-control-sm shadow-sm" value={type} onChange={this.onChangeType}>178                                <FormattedMessage id="select-type">179                                    {(message) => <option value={0} disabled> {message} </option>}180                                </FormattedMessage>181                                <FormattedMessage id="yes-no">182                                    {(message) => <option value={1}> {message} </option>}183                                </FormattedMessage>184                                <FormattedMessage id="single-choice">185                                    {(message) => <option value={2}> {message} </option>}186                                </FormattedMessage>187                                <FormattedMessage id="multi-choice">188                                    {(message) => <option value={3}> {message} </option>}189                                </FormattedMessage>190                            </select>191                        </div>192                        {193                            this.renderSwitch(alternatives)194                        }195                        {196                            errors ?197                                <Alert color="danger" isOpen={toggleAlert} toggle={this.onToggleAlert} className="col-md-12 mt-2 px-4">198                                    <i className="fa fa-exclamation-circle" aria-hidden="true"/> {errors}199                                </Alert>200                                :201                                null202                        }203                        <button type="button" className="btn btn-md my-btn-outline-success ml-auto mt-2 shadow" onClick={this.onQuestionSubmit}>204                            <i className="fa fa-floppy-o" aria-hidden="true"/> {translate('save-question')}205                        </button>206                    </div>207                </div>208            </div>209        )210    }211}...

Full Screen

Full Screen

script.js

Source:script.js Github

copy

Full Screen

1/*  https://www.welovequizzes.com/countries-of-the-world-quiz-questions-and-answers/ */2/*3let currentQuestion = 0;4let currentScore = 0;5*/6/**7 * List of questions8 */9let questionList = [{10    questionText: 'What is the smallest country in the world with an area of only 0.49 square kilometres?',11    alternatives: ['Monaco', 'Vatican', 'Andorra'],12    answer: 113},14{15    questionText: 'What is the second-largest country in the world after Russia?',16    alternatives: ['China', 'USA', 'Canada'],17    answer: 218},19{20    questionText: 'Which of the following is a landlocked country, meaning it is not bordered by the sea or ocean?',21    alternatives: ['Kazakhstan', 'Madagascar', 'Turkey'],22    answer: 023},24{25    questionText: 'Which of the following countries is not in Central America?',26    alternatives: ['Cuba', 'Mexic', 'Uruguay'],27    answer: 228},29{30    questionText: 'Which of the following countries has the largest Muslim population in the world?',31    alternatives: ['Saudi Arabia', 'Indonesia', 'Iran'],32    answer: 133},34{35    questionText: 'Which European country is divided into administrative divisions called departments?',36    alternatives: ['France', 'Spain', 'Portugal'],37    answer: 038},39{40    questionText: 'Which of the following countries is shaped like a high heel boot?',41    alternatives: ['Chile', 'Finland', 'Italy'],42    answer: 243},44{45    questionText: 'Mouth Kilimanjaro, the highest mountain in Africa, is located in which country?',46    alternatives: ['Kenya', 'Tanzania', 'Lesotho'],47    answer: 148},49{50    questionText: 'In which country can you visit Machu Picchu, which used to be the citadel of the Inca Empire?',51    alternatives: ['Guatemala', 'Peru', 'Bolivia'],52    answer: 153},54{55    questionText: 'Pho, which contains beef, herbs, rice noodles, and broth, is a traditional dish in which Asian country?',56    alternatives: ['Cambodia', 'Vietnam', 'Malaysia'],57    answer: 158},59{60    questionText: 'Which of the following countries is often regarded as the oldest republic in the world?',61    alternatives: ['Greece', 'Italy', 'San Marino'],62    answer: 263},64{65    questionText: 'Which country will host the 2024 Olympics Summer Games?',66    alternatives: ['France', 'Australia', 'Japan'],67    answer: 068},69{70    questionText: 'Which country has the most islands in the world with more than 221,800?',71    alternatives: ['Canada', 'Norway', 'Sweden'],72    answer: 273},74{75    questionText: 'Which country is often called Land of Rising Sun?',76    alternatives: ['China', 'Japan', 'South Korea'],77    answer: 178},79{80    questionText: 'On 15 August 1947, British India was separated into India and which modern-day country?',81    alternatives: ['Pakistan', 'Bangladesh', 'Nepal'],82    answer: 083},84{85    questionText: 'Which country in eastern Europe used to be known as White Russia?',86    alternatives: ['Ukraina', 'Belarus', 'Bulgaria'],87    answer: 188},89{90    questionText: 'Kimono is the national dress of which country?',91    alternatives: ['South Korea', 'China', 'Japan'],92    answer: 293},94{95    questionText: 'Guitar is originated from which country in the 16th century?',96    alternatives: ['Greece', 'France', 'Spain'],97    answer: 298},99{100    questionText: 'What is the most populous country in the European Union?',101    alternatives: ['Russia', 'Germany', 'France'],102    answer: 1103},104{105    questionText: 'Which two nations share the longest border in the world?',106    alternatives: ['USA and Canada', 'China and Russia', 'Brazil and Argentina'],107    answer: 0108},109{110    questionText: 'Which of the following island countries is located on the Pacific Ocean?',111    alternatives: ['Tuvalu', 'Jamaica', 'Malta'],112    answer: 0113},114{115    questionText: 'Dirham is the official currency of which country?',116    alternatives: ['Iraq', 'Egypt', 'United Arab Emirates'],117    answer: 2118},119{120    questionText: 'The unicorn is the official national animal of which country?',121    alternatives: ['Wales', 'Northern Ireland', 'Scotland'],122    answer: 2123},124{125    questionText: 'Which of the following countries is not a Nordic country?',126    alternatives: ['Iceland', 'Russia', 'Denmark'],127    answer: 1128},129{130    questionText: 'What is the only country in the world that has a national flag that is not rectangular?',131    alternatives: ['Nepal', 'Switzerland', 'Kyrgyzstan'],132    answer: 0133},134{135    questionText: 'What is the first country in the world to grant the vote to women?',136    alternatives: ['Australia', 'New Zealand', 'Canada'],137    answer: 1138},139{140    questionText: 'Which country was called Santiago when Christopher Columbus first discovered it in 1494?',141    alternatives: ['Panama', 'Cuba', 'Jamaica'],142    answer: 2143},144{145    questionText: 'The Nobel Peace Prize is held every year in which country?',146    alternatives: ['Denmark', 'Sweden', 'Norway'],147    answer: 2148},149{150    questionText: 'In which country do people say “Shalom” to greet people?',151    alternatives: ['Israel', 'Egypt', 'Jordan'],152    answer: 0153},154{155    questionText: 'Which country is the current world’s leader in coffee exporting?',156    alternatives: ['Indonesia', 'Colombia', 'Brazil'],157    answer: 2158},159{160    questionText: 'Which modern-day country is considered to be the successor of the Ottoman Empire?',161    alternatives: ['Lebanon', 'Turkey', 'Jordan'],162    answer: 1163},164{165    questionText: '“God Save the Queen” is the national anthem of which country?',166    alternatives: ['Vatican', 'France', 'The United Kingdom'],167    answer: 2168},169{170    questionText: 'Which is the newest member of the United Nations, which declared its independence in 2011?',171    alternatives: ['South Sudan', 'Kosovo', 'East Timor'],172    answer: 0173},174{175    questionText: 'The Chernobyl disaster, which is considered the worst nuclear accident in history in terms of casualties and cost, occurred in 1986 in which country?',176    alternatives: ['Ukraine', 'Russia', 'Moldova'],177    answer: 0178},179{180    questionText: 'In which country can you find the “Door to Hell”, a natural gas pit that has been on fire since 1971?',181    alternatives: ['Georgia', 'Azerbaijan', 'Turkmenistan'],182    answer: 2183},184{185    questionText: 'The Strait of Gibraltar separates Spain and Portugal from which country?',186    alternatives: ['Tunisia', 'Morocco', 'Algeria'],187    answer: 1188},189{190    questionText: 'In which of the following country do people drive their vehicles on the left of the road?',191    alternatives: ['China', 'Estonia', 'Australia'],192    answer: 2193},194{195    questionText: 'In which country was the first national park in the world was established in 1872?',196    alternatives: ['The United States', 'France', 'Germany'],197    answer: 0198}];199/**200 * Start quiz when user hit start201 * Alter HTML to launch question and alternatives202*/203var quizArea = document.getElementById('game-area');204var question = document.getElementById('questionDiv');205var alternative1 = document.getElementById('alt1');206var alternative2 = document.getElementById('alt2');207var alternative3 = document.getElementById('alt3');208function startQuiz() { // event listener for start button209    210    quizArea.innerHTML = `211        <div onload="loaded()"; id="questionDiv">212        ${questionList[0].questionText}213        </div>214        <button onclick="alt1();" id="alt1" class="alt1 alt-button" aria-label="Alternative 1">215        ${questionList[0].alternatives[0]}216        </button>217        218        <button onclick="alt2();" id="alt2" class="alt2 alt-button" aria-label="Alternativ 2">219        ${questionList[0].alternatives[1]}220        </button>221        <button onclick="alt3();" id="alt3" class="alt3 alt-button" aria-label="Alternative 3">222        ${questionList[0].alternatives[2]}223        </button>224        <div class="footer">225            <div class="score-counter">226            </div>227            228            <button onclick="nextQuestion();" class="next-button">Next</button>229            230        </div>         231    `;232}233/*234function nextQuestion() {235    currentQuestion = 1;236    question.innerHTML = questionList[currentQuestion].questionText;237}238*/239/**240* Pull next question from array241*/  242/*243function nextQuestion() { // event listener for the next button244    let question = document.getElementById('questionDiv');245    let arrayLength = questionList.length;246    for (let i = 0; i < arrayLength; i++) {247        arrayLength.questionText;248        249    }250    question.innerText = questionList[0].questionText;251}252/**253* Pull next question from array254*/  255/*256let arrayLength = questionList.length;257function nextQuestion() {258    for (i = 0; i < arrayLength; i++) {259        questionList[i].questionText;260    console.log(arrayLength); // Control output    261    }262}263*/264/**265 * Correct answer validator266 */267/*268let correctAnswer = questionList[0].answer269function answerValidator() {270    if questionList.alternatives[0] === questionList.answer271} else {272    questionList.alternatives[1] === questionList.answer273} else {274    questionList.alternatives[2] === questionList.answer275}276    277*/278/*279function alt1() {280console.log("test 1");281}282function alt2() {283console.log("test 2");284}285function alt3() {286    console.log("test 3");287}288*/289 /**290  * Score board ...

Full Screen

Full Screen

suggestAlternatives.js

Source:suggestAlternatives.js Github

copy

Full Screen

1/*---------------------------------------------------------------------------------------------2 *  Copyright (c) Microsoft Corporation. All rights reserved.3 *  Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {6    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;7    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);8    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;9    return c > 3 && r && Object.defineProperty(target, key, r), r;10};11var __param = (this && this.__param) || function (paramIndex, decorator) {12    return function (target, key) { decorator(target, key, paramIndex); }13};14import { dispose } from '../../../base/common/lifecycle.js';15import { IContextKeyService, RawContextKey } from '../../../platform/contextkey/common/contextkey.js';16var SuggestAlternatives = /** @class */ (function () {17    function SuggestAlternatives(_editor, contextKeyService) {18        this._editor = _editor;19        this._ckOtherSuggestions = SuggestAlternatives.OtherSuggestions.bindTo(contextKeyService);20    }21    SuggestAlternatives.prototype.dispose = function () {22        this.reset();23    };24    SuggestAlternatives.prototype.reset = function () {25        this._ckOtherSuggestions.reset();26        dispose(this._listener);27        this._model = undefined;28        this._acceptNext = undefined;29        this._ignore = false;30    };31    SuggestAlternatives.prototype.set = function (_a, acceptNext) {32        var _this = this;33        var model = _a.model, index = _a.index;34        // no suggestions -> nothing to do35        if (model.items.length === 0) {36            this.reset();37            return;38        }39        // no alternative suggestions -> nothing to do40        var nextIndex = SuggestAlternatives._moveIndex(true, model, index);41        if (nextIndex === index) {42            this.reset();43            return;44        }45        this._acceptNext = acceptNext;46        this._model = model;47        this._index = index;48        this._listener = this._editor.onDidChangeCursorPosition(function () {49            if (!_this._ignore) {50                _this.reset();51            }52        });53        this._ckOtherSuggestions.set(true);54    };55    SuggestAlternatives._moveIndex = function (fwd, model, index) {56        var newIndex = index;57        while (true) {58            newIndex = (newIndex + model.items.length + (fwd ? +1 : -1)) % model.items.length;59            if (newIndex === index) {60                break;61            }62            if (!model.items[newIndex].completion.additionalTextEdits) {63                break;64            }65        }66        return newIndex;67    };68    SuggestAlternatives.prototype.next = function () {69        this._move(true);70    };71    SuggestAlternatives.prototype.prev = function () {72        this._move(false);73    };74    SuggestAlternatives.prototype._move = function (fwd) {75        if (!this._model) {76            // nothing to reason about77            return;78        }79        try {80            this._ignore = true;81            this._index = SuggestAlternatives._moveIndex(fwd, this._model, this._index);82            this._acceptNext({ index: this._index, item: this._model.items[this._index], model: this._model });83        }84        finally {85            this._ignore = false;86        }87    };88    SuggestAlternatives.OtherSuggestions = new RawContextKey('hasOtherSuggestions', false);89    SuggestAlternatives = __decorate([90        __param(1, IContextKeyService)91    ], SuggestAlternatives);92    return SuggestAlternatives;93}());...

Full Screen

Full Screen

generateAlternatives.test.js

Source:generateAlternatives.test.js Github

copy

Full Screen

1import generateAlternatives from '../src/utils/generateAlternatives';2test('gerar alternativas não traduzida', () => {3  const lineBinaryCode = [[1, 0, 1, 0, 0]];4  const result = generateAlternatives(lineBinaryCode, false);5  console.log(result);6  expect(result[0].text).toBe('1,0,1,0,0');7  expect(alternativesAreDifferent(result)).toBeTruthy();8});9test('gerar alternativas traduzida', () => {10  const lineBinaryCode = [[1, 0, 1, 0, 0]];11  const result = generateAlternatives(lineBinaryCode, true);12  console.log(result);13  expect(result[0].text).toBe('1,1,1,2');14  expect(alternativesAreDifferent(result)).toBeTruthy();15});16test('deve traduzir [0, 1, 1, 1, 1] para run lenght code', () => {17  const lineBinaryCode = [[0, 1, 1, 1, 1]];18  const result = generateAlternatives(lineBinaryCode, true);19  console.log(result);20  expect(result[0].text).toBe('0,1,4');21  expect(alternativesAreDifferent(result)).toBeTruthy();22});23test('não deve traduzir [0,0,1,0,0] para run lenght code', () => {24  const lineBinaryCode = [[0, 0, 1, 0, 0]];25  const result = generateAlternatives(lineBinaryCode, false);26  console.log(result);27  expect(result[0].text).toBe('0,0,1,0,0');28  expect(alternativesAreDifferent(result)).toBeTruthy();29});30test('deve traduzir [0,0,0,0,0] para run lenght code', () => {31  const lineBinaryCode = [[0, 0, 0, 0, 0]];32  const result = generateAlternatives(lineBinaryCode, true);33  console.log(result);34  expect(result[0].text).toBe('0,5');35  expect(alternativesAreDifferent(result)).toBeTruthy();36});37test('nao deve traduzir [0,0,0,0,0] para run lenght code', () => {38  const lineBinaryCode = [[0, 0, 0, 0, 0]];39  const result = generateAlternatives(lineBinaryCode, false);40  console.log(result);41  expect(result[0].text).toBe('0,0,0,0,0');42  expect(alternativesAreDifferent(result)).toBeTruthy();43});44test('deve traduzir [1,1,1,1,1] para run lenght code', () => {45  const lineBinaryCode = [[1, 1, 1, 1, 1]];46  const result = generateAlternatives(lineBinaryCode, true);47  console.log(result);48  expect(result[0].text).toBe('5');49  expect(alternativesAreDifferent(result)).toBeTruthy();50});51test('não deve traduzir [1,1,1,1,1] para run lenght code', () => {52  const lineBinaryCode = [[1, 1, 1, 1, 1]];53  const result = generateAlternatives(lineBinaryCode, false);54  console.log(result);55  expect(result[0].text).toBe('1,1,1,1,1');56  expect(alternativesAreDifferent(result)).toBeTruthy();57});58const alternativesAreDifferent = (result) => {59  for (let i = 0; i < result.length; i += 1) {60    const currentText = result[i].text;61    for (let j = 0; j < result.length; j += 1) {62      if (i !== j && currentText === result[j].text) {63        return false;64      }65    }66  }67  return true;68};69test('deve traduzir [2, 2, 2, 3, 1] para run lenght code colorful', () => {70  const lineBinaryCode = [[2, 2, 2, 3, 1]];71  const result = generateAlternatives(lineBinaryCode, true, false, true);72  console.log(result);73  expect(result[0].text).toBe('3-2,1-3,1-1');74  expect(alternativesAreDifferent(result)).toBeTruthy();...

Full Screen

Full Screen

AlternativesEditor.js

Source:AlternativesEditor.js Github

copy

Full Screen

1import React, { Fragment, useContext } from 'react';2import AlternativeEditor from './AlternativeEditor';3import { Dispatch, State } from '../../context';4/**5 * Synonyms editor component.6 *7 * @param {Object} props Props.8 * @param {Object[]} props.alternatives Defined alternatives (explicit mappings).9 * @return {React.FC} AlternativesEditor component10 */11const AlternativesEditor = ({ alternatives }) => {12	const dispatch = useContext(Dispatch);13	const state = useContext(State);14	const {15		alternativesInputHeading,16		alternativesPrimaryHeading,17		alternativesAddButtonText,18		alternativesErrorMessage,19	} = window.epSynonyms.i18n;20	/**21	 * Handle click.22	 *23	 * @param {React.SyntheticEvent} e Event.24	 */25	const handleClick = (e) => {26		const [lastItem] = state.alternatives.slice(-1);27		if (!alternatives.length || lastItem.synonyms.filter(({ value }) => value.length).length) {28			dispatch({ type: 'ADD_ALTERNATIVE' });29		}30		e.preventDefault();31	};32	return (33		<div className="synonym-alternatives-editor metabox-holder">34			<div className="postbox">35				<h2 className="hndle">36					<span className="synonym-alternatives__primary-heading">37						{alternativesPrimaryHeading}38					</span>39					<span className="synonym-alternatives__input-heading">40						{alternativesInputHeading}41					</span>42				</h2>43				<div className="inside">44					{alternatives.map((props) => (45						<Fragment key={props.id}>46							<div className="synonym-alternative-editor">47								<AlternativeEditor48									{...props}49									updateAction="UPDATE_ALTERNATIVE"50									removeAction="REMOVE_ALTERNATIVE"51								/>52							</div>53							{!props.valid && (54								<p className="synonym__validation">{alternativesErrorMessage}</p>55							)}56						</Fragment>57					))}58					<button type="button" className="button button-secondary" onClick={handleClick}>59						{alternativesAddButtonText}60					</button>61				</div>62			</div>63		</div>64	);65};...

Full Screen

Full Screen

generateAlternatives.js

Source:generateAlternatives.js Github

copy

Full Screen

1/* eslint-disable no-plusplus */2import randomRowValue from './randomRowValue';3import translateRunLenghtCode from './translateRunLenghtCode';4const alternativesContains = (alternatives, alternative) => {5  const alternativeMapResult = alternatives.map((item) => {6    const isSame = item.toString() === alternative.toString();7    return isSame;8  });9  return alternativeMapResult.includes(true);10};11const generateAlternatives = (12  lineBinaryCode,13  isTranslate,14  isTranslateCorrect,15  isColorFul,16) => {17  if (!lineBinaryCode || lineBinaryCode.length === 0) return [];18  const alternatives = [];19  const alternativesObj = [];20  const maxAlternatives = 4;21  const numColumns = 5;22  alternatives.push(23    !isTranslateCorrect && isTranslate24      ? translateRunLenghtCode(lineBinaryCode[0], isColorFul)25      : lineBinaryCode[0],26  );27  alternativesObj.push({28    id: 1,29    text: alternatives[0].join(),30    correct: true,31  });32  while (alternatives.length !== maxAlternatives) {33    const nextAlternative = isTranslate34      ? translateRunLenghtCode(randomRowValue(numColumns), isColorFul)35      : randomRowValue(numColumns);36    if (!alternativesContains(alternatives, nextAlternative)) {37      alternatives.push(nextAlternative);38    }39  }40  for (let i = 1; i < maxAlternatives; i++) {41    alternativesObj.push({42      id: i + 1,43      text: alternatives[i].join(),44      correct: false,45    });46  }47  return alternativesObj;48};...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

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