Best JavaScript code snippet using jest
wikiParser.js
Source:wikiParser.js
1var monthsList = {2 1: "January",3 2: "February",4 3: "March",5 4: "April",6 5: "May",7 6: "June",8 7: "July",9 8: "August",10 9: "September",11 10: "October",12 11: "November",13 12: "December"14};1516var singleParserRegex = /=== ?[A-Z]\w+ ?===/;1718var rangedParserRegex = /=== [A-Z]\w+(–|\â)[A-Z]\w+ ===/;1920// Callback for Wikipedia.21function getWiki(wikiObject) {22 var article = getWikiDateEvent(wikiObject);2324 var modalTitle = document.getElementById("ModalCenterTitle");25 modalTitle.innerHTML = monthsList[month] + " " + day + ", " + year;2627 var modalBody = document.getElementsByClassName("modal-body")[0];28 modalBody.innerHTML = article;2930 article = article.replace(" ", "%20"); 3132 var twitterButton = document.querySelector(".twitter-share-button");33 if(twitterButton == null)34 twitterButton = document.createElement("a");3536 twitterButton.setAttribute("class", "twitter-share-button");37 twitterButton.setAttribute("href", "https://twitter.com/intent/tweet?text=On%20"+38 monthsList[month] + " " + day + ", " +39 year + article + "%20&button_hashtag=timeTravel");40 twitterButton.setAttribute("data-size", "large");41 twitterButton.innerHTML = '<img src="images/twitter_share.png" width="80" height="40" ></img>';4243 var modalFooter = document.querySelector(".modal-footer");44 modalFooter.appendChild(twitterButton);45}4647function getWikiDateEvent(wikiObject) {48 var wikiPages = wikiObject.query.pages;49 var wikiResponse = wikiPages[Object.keys(wikiPages)[0]].revisions[0]["*"]50 var birthStartIndex = wikiResponse.search(/(===?) ?Births ?(===?)/);51 wikiResponse = wikiResponse.slice(0, birthStartIndex);5253 // Parser Single Regex /===[A-Z]\w+===/54 // Parser Mix Regex /=== [A-Z]\w+ndash;[A-Z]\w+===/5556 //var isSingleParser = wikiResponse.search(/===[A-Z]\w+===/);57 var isMixParser = wikiResponse.search(rangedParserRegex);58 var dateInfo = ""5960 console.log(wikiResponse);61 if(isMixParser == -1){62 var monthEvents = parserSingle(wikiResponse);63 dateInfo = getDateInfo(monthEvents, monthsList[month], day);64 } else {65 var monthEvents = parserRange(wikiResponse);66 dateInfo = getDateInfo(monthEvents, monthsList[month], day);67 }6869 return dateInfo;70}71// Returns an array containing Month with Events.72// getDateInfo function can help for further parsing.73function parserSingle(wikiResponse){74 var firstMonthIndex = wikiResponse.search(singleParserRegex);75 var responseToSplit = wikiResponse.substr(firstMonthIndex, wikiResponse.length);76 var tidyMonthEvents = responseToSplit.split("===", 25);7778 // Prepare an Array with key [Month] value [Content]79 var monthEvents = new Array();80 for(var i = 0; i < tidyMonthEvents.length; i+=2){81 if(tidyMonthEvents[i] == ""){82 i+=1;83 }84 var months = tidyMonthEvents[i].trim();85 var content = tidyMonthEvents[i+1];86 monthEvents[months] = content;87 }88 return monthEvents;89}9091// TODO: Define events for months in a range ex: Jan-Apr you also need to add february and march,92// because they may have events93function parserRange(wikiResponse){94 9596 console.log(wikiResponse);97 // – is the base character for this parser to work.98 var firstMonthIndex = wikiResponse.search(rangedParserRegex);99 var responseToSplit = wikiResponse.substr(firstMonthIndex, wikiResponse.length);100 var tidyMonthEvents = responseToSplit.split("===", 25);101 console.log(tidyMonthEvents);102103 // Prepare an Array with key [Month] value [Content]104 var monthEvents = new Array();105 106 for(var i = 0; i < tidyMonthEvents.length; i+=2){107 if(tidyMonthEvents[i] == ""){108 i+=1;109 }110 var splitTo = "–";111 if(tidyMonthEvents[i].indexOf("–") == -1){112 splitTo = "â";113 }114 var months = tidyMonthEvents[i].trim().split(splitTo);115 var rangeFirstMonth = getObjKeyByVal(monthsList, months[0], 1);116 var rangeLastMonth = getObjKeyByVal(monthsList, months[1], 1);117118 months = objectSliceByIndex(monthsList, rangeFirstMonth, rangeLastMonth);119 var content = tidyMonthEvents[i+1];120121 for (prop in months) {122 monthEvents[months[prop]] = content;123 }124 }125126 return monthEvents;127}128129// Return the Article with the month and day specified.130function getDateInfo(monthEvents, month, day) {131 if(!(month in monthEvents)){132 return "Nothing happened in this month.";133 }134 var monthExist = monthEvents[month].search(month + " " + day + "]");135 if(monthExist < 0){136 return "Nothing has happened at this date!";137 }138139 var monthEventsArray = monthEvents[month].replace(/[&\/\\#,+()$~%.'":?<>{}\[\]]/g, '')140 .replace(/\* ?[A-Z]\w+ \d{1,2}(?!\w)/g, "~$&");141142 monthEventsArray = monthEventsArray.split("~*");143 var article = "";144145 for(var i = 1; i < monthEventsArray.length; i++)146 {147 var item = monthEventsArray[i];148 if(item.search(month + " " + day) != -1){149 article = item;150 break;151 }152 }153154 dashIndex = article.indexOf(";");155 if(dashIndex == -1){156 dashIndex = article.indexOf("â");157 } if(dashIndex == -1) {158 dashIndex = article.indexOf("\n");159 }160161 if(dashIndex != -1) {162 article = article.slice(dashIndex+1, article.length);163 }164 article = article.replace(/[&\/\\#,+()$~%.'":*?<>{}\[\]]/g, '');165 console.log(article[10]);166 return article;167}168169function escapeRegExp(string) {170 return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string171}172173function getObjKeyByVal(obj, val, offset=0) {174 var index = offset;175 for (var value in obj){176 if (obj[value] === val) {177 return index;178 }179 index++;180 }181 return false;182}183184function objectSliceByIndex(obj, start, end) {185 var slicedObj = {};186 for(var i = start; i <= end; i++) {187 slicedObj[i] = obj[i];188 }189 return slicedObj;
...
twitter-client.js
Source:twitter-client.js
1/* eslint-env browser */2/* global $ */3"use strict";4var formField = require("../ui/utils/form-field.js"),5 twitterUsername;6module.exports = function(core) {7 // Twitter integration8 core.on("conf-show", function(tabs, next) {9 var $div = $("<div>"),10 results = tabs.room,11 twitter = results.params.twitter;12 if (!twitter) {13 twitter = {};14 }15 twitterUsername = twitter.username;16 var $twitterTags = formField("Hashtags", "multientry", "twitter-hashtags", twitter.tags),17 $twitterButton = $("<a>").addClass("button twitter").attr("id", "twitter-account"),18 $twitterAccount = formField("", "", "twitter-text", $twitterButton),19 $twitterMsg = formField("", "info", "twitter-message-text", ""),20 $twitterString = $twitterMsg.find("#twitter-message-text"),21 updateFields = function() {22 if (twitterUsername) {23 $twitterButton.removeClass("twitter-signed-out");24 $twitterButton.addClass("twitter-signed-in");25 $twitterButton.text("Remove account");26 $twitterAccount.find(".settings-label").text("Signed in as " + twitterUsername);27 $twitterString.empty();28 } else {29 $twitterButton.removeClass("twitter-signed-in");30 $twitterButton.addClass("twitter-signed-out");31 $twitterButton.text("Sign in to Twitter");32 $twitterAccount.find(".settings-label").text("Not signed in");33 $twitterString.text("Please sign in to Twitter to watch hashtags");34 }35 };36 $twitterButton.on("click", function() {37 // do stuff here!38 if ($twitterButton.hasClass("twitter-signed-out")) {39 window.open("../r/twitter/login", "mywin", "left=20,top=20,width=500,height=500,toolbar=1,resizable=0");40 } else if ($twitterButton.hasClass("twitter-signed-in")) {41 twitterUsername = null;42 updateFields();43 }44 });45 $(window).on("message", function(e) {46 var suffix = "scrollback.io", data,47 isOrigin = e.originalEvent.origin.indexOf(suffix, e.originalEvent.origin.length - suffix.length) !== -1;48 data = e.originalEvent.data;49 try {50 data = JSON.parse(e.originalEvent.data);51 } catch (err) {52 return;53 }54 if (!isOrigin || !data.twitter ) { return; }55 twitterUsername = data.twitter.username;56 updateFields();57 });58 updateFields();59 $div.append(60 $twitterTags,61 $twitterAccount,62 $twitterMsg63 );64 tabs.twitter = {65 text: "Twitter integration",66 html: $div67 };68 next();69 }, 600);70 core.on("conf-save", function(room, next) {71 var tags = $("#twitter-hashtags").multientry("items", true).join(" ");72 room.params.twitter = {};73 if (tags || twitterUsername) {74 room.params.twitter = {75 tags: tags,76 username: twitterUsername77 };78 }79 next();80 }, 500);...
storyProgess.js
Source:storyProgess.js
1var storyCounter = 0;2function storyProgressFunction(event){3 if(storyCounter < enemyCharacter[questionCounter].prestory.length - 1){4 storyCounter += 1;5 displayStory(enemyCharacter[questionCounter].prestory[storyCounter][0]);6 }else{7 storyCounter = 0;8 if(enemyCharacter[questionCounter].enemy){9 initialEnemyHealth();10 }11 if(questionCounter === 0){12 enemyCharacter[0].enemyBackgroundMusicChange();13 }if(questionCounter < 10){14 changeQuestion(encounterArray[questionCounter][0], encounterArray[questionCounter][1], encounterArray[questionCounter][2], encounterArray[questionCounter][3], encounterArray[questionCounter][4]);15 }else{16 youWin();17 }18 }19}20function displayStory(storyText){21 var textField = document.getElementsByClassName('textField')[0];22 while (textField.hasChildNodes()) {23 textField.removeChild(textField.lastChild);24 };25 var speakingField = document.createElement('h2');26 textField.appendChild(speakingField);27 var promptField = document.createElement('p');28 promptField.innerText = storyText;29 textField.appendChild(promptField);30 var unList = document.createElement('ul');31 textField.appendChild(unList);32 var choiceOne = document.createElement('li');33 choiceOne.innerText = 'Continue';34 choiceOne.setAttribute('id', 'continueButton');35 textField.appendChild(choiceOne);36 choiceOne.addEventListener('click', storyProgressFunction);37}38function youWin(){39 var textField = document.getElementsByClassName('textField')[0];40 while (textField.hasChildNodes()) {41 textField.removeChild(textField.lastChild);42 };43 var speakingField = document.createElement('h2');44 var totalScore = (userCharacter.str + userCharacter.agil + userCharacter.int + userCharacter.hp) * 1000;45 speakingField.innerText = userCharacter.name + '\'s score was: ' + totalScore;46 textField.appendChild(speakingField);47 var promptField = document.createElement('p');48 promptField.innerText = 'You Won!';49 promptField.setAttribute('class', 'gameOver');50 promptField.addEventListener('click', resetGame);51 textField.appendChild(promptField);52 var twitterDiv = document.createElement('div');53 twitterDiv.setAttribute('class', 'finalScoreTwitter');54 var twitterButton = document.createElement('a');55 twitterButton.setAttribute('class', 'twitter-share-button');56 twitterButton.setAttribute('href', 'https://twitter.com/share');57 twitterButton.setAttribute('data-size', 'large');58 var twitterMessage = 'I just escaped @GhostownGame! I got ' + totalScore + ' points! Can you survive? Try at.';59 twitterButton.setAttribute('data-text', twitterMessage);60 twitterButton.setAttribute('data-url', 'http://www.ghostowngame.com');61 twitterButton.setAttribute('data-hashtags', 'gamedev, indiedev, ghostown');62 twitterButton.setAttribute('data-related', 'twitterapi, ghostowngame');63 twitterButton.innerText = 'Post a Tweet!';64 twitterDiv.appendChild(twitterButton);65 textField.appendChild(twitterDiv);66 twttr.widgets.load();...
index.js
Source:index.js
1/* eslint-disable */2import React from 'react';3import TwitterButton from './TwitterButton';4const demoCode = `5 import React from 'react';6 import GradientButton from './GradientButton';7 8 const Demo = () => (9 <>10 <GradientButton>Cool</GradientButton>11 <GradientButton chubby>Chubby</GradientButton>12 </>13 )14 15 export default Demo;16`;17TwitterButton.Demo = () => (18 <>19 <TwitterButton color={'primary'} variant={'contained'}>20 Normal21 </TwitterButton>22 <TwitterButton color={'primary'} variant={'contained'} size={'large'}>23 Large Button24 </TwitterButton>25 <TwitterButton variant={'outlined'} color={'primary'}>26 Normal27 </TwitterButton>28 <TwitterButton variant={'outlined'} color={'primary'} size={'large'}>29 Large Button30 </TwitterButton>31 </>32);33const twitterCode = `34 import React from 'react';35 import Button from '@material-ui/core/Button';36 import { makeStyles } from '@material-ui/styles';37 38 const useStyles = makeStyles(({ shadows, palette }) => ({39 root: {40 borderRadius: 100,41 minHeight: 30,42 padding: '0 1em',43 },44 label: {45 textTransform: 'none',46 fontSize: 15,47 fontWeight: 700,48 },49 outlined: {50 padding: '0 1em',51 },52 outlinedPrimary: {53 borderColor: 'rgb(29, 161, 242)',54 color: 'rgb(29, 161, 242)',55 '&:hover': {56 borderColor: 'rgb(29, 161, 242)',57 color: 'rgb(29, 161, 242)',58 backgroundColor: 'rgb(29, 161, 242, 0.1)',59 },60 },61 contained: {62 minHeight: 30,63 boxShadow: shadows[0],64 '&$focusVisible': {65 boxShadow: shadows[0],66 },67 '&:active': {68 boxShadow: shadows[0],69 },70 '&$disabled': {71 boxShadow: shadows[0],72 },73 },74 containedPrimary: {75 backgroundColor: 'rgb(29, 161, 242)',76 color: palette.common.white,77 '&:hover': {78 backgroundColor: 'rgb(29, 145, 218)',79 // Reset on touch devices, it doesn't add specificity80 '@media (hover: none)': {81 backgroundColor: 'rgb(29, 145, 218)',82 },83 },84 },85 sizeLarge: {86 padding: '0 1em',87 minHeight: 39,88 },89 }));90 91 const TwitterButton = ({ ...props }) => {92 const classes = useStyles();93 return <Button classes={classes} {...props} />;94 };95 96 export default TwitterButton;97`;98TwitterButton.info = {99 name: 'Twitter Button',100 description: 'Tweet',101 links: [102 { label: 'Code Sandbox', url: 'https://codesandbox.io/s/5xj8vn1k1l' },103 { label: 'Full API', url: 'https://material-ui.com/api/button/' },104 ],105 files: [106 {107 label: 'Demo.js',108 code: demoCode,109 },110 {111 label: 'TwitterButton.js',112 code: twitterCode,113 },114 ],115 libraries: [],116 dependencies: ['@material-ui/core'],117};118TwitterButton.codeSandbox = 'https://codesandbox.io/s/5xj8vn1k1l';...
twitterButtonDoc.js
Source:twitterButtonDoc.js
1/* eslint-disable */2import React from 'react';3import TwitterButton from 'components/buttons/TwitterButton';4const demoCode = `5 import React from 'react';6 import GradientButton from './GradientButton';7 8 const Demo = () => (9 <>10 <GradientButton>Cool</GradientButton>11 <GradientButton chubby>Chubby</GradientButton>12 </>13 )14 15 export default Demo;16`;17TwitterButton.Demo = () => (18 <>19 <TwitterButton color={'primary'} variant={'contained'}>20 Normal21 </TwitterButton>22 <TwitterButton color={'primary'} variant={'contained'} size={'large'}>23 Large Button24 </TwitterButton>25 <TwitterButton variant={'outlined'} color={'primary'}>26 Normal27 </TwitterButton>28 <TwitterButton variant={'outlined'} color={'primary'} size={'large'}>29 Large Button30 </TwitterButton>31 </>32);33const twitterCode = `34 import React from 'react';35 import Button from '@material-ui/core/Button';36 import { makeStyles } from '@material-ui/styles';37 38 const useStyles = makeStyles(({ shadows, palette }) => ({39 root: {40 borderRadius: 100,41 minHeight: 30,42 padding: '0 1em',43 },44 label: {45 textTransform: 'none',46 fontSize: 15,47 fontWeight: 700,48 },49 outlined: {50 padding: '0 1em',51 },52 outlinedPrimary: {53 borderColor: 'rgb(29, 161, 242)',54 color: 'rgb(29, 161, 242)',55 '&:hover': {56 borderColor: 'rgb(29, 161, 242)',57 color: 'rgb(29, 161, 242)',58 backgroundColor: 'rgb(29, 161, 242, 0.1)',59 },60 },61 contained: {62 minHeight: 30,63 boxShadow: shadows[0],64 '&:active': {65 boxShadow: shadows[0],66 },67 },68 containedPrimary: {69 backgroundColor: 'rgb(29, 161, 242)',70 color: palette.common.white,71 '&:hover': {72 backgroundColor: 'rgb(29, 145, 218)',73 // Reset on touch devices, it doesn't add specificity74 '@media (hover: none)': {75 backgroundColor: 'rgb(29, 145, 218)',76 },77 },78 },79 sizeLarge: {80 padding: '0 1em',81 minHeight: 39,82 },83 }));84 85 const TwitterButton = props => {86 const classes = useStyles(props);87 return <Button {...props} classes={classes} />;88 };89 90 export default TwitterButton;91`;92TwitterButton.info = {93 name: 'Twitter Button',94 description: 'Tweet',95 links: [96 { label: 'Code Sandbox', url: 'https://codesandbox.io/s/5xj8vn1k1l' },97 { label: 'Button API', url: 'https://material-ui.com/api/button/' },98 {99 label: 'Styling',100 url: 'https://material-ui.com/styles/basics/#hook-api',101 },102 ],103 files: [104 {105 label: 'Demo.js',106 code: demoCode,107 },108 {109 label: 'TwitterButton.js',110 code: twitterCode,111 },112 ],113 libraries: [],114 dependencies: ['@material-ui/core'],115};116TwitterButton.codeSandbox = 'https://codesandbox.io/s/5xj8vn1k1l';...
social_login_button_spec.js
Source:social_login_button_spec.js
1// Copyright (c) 2010-2011, Nathan Sobo and Max Brunsfeld. This file is2// licensed under the Affero General Public License version 3 or later. See3// the COPYRIGHT file.4describe("Views.Components.SocialLoginButton", function() {5 var facebookButton, twitterButton, fb;6 beforeEach(function() {7 fb = window.FB;8 window.FB = undefined;9 renderLayout();10 facebookButton = Application.loginForm.show().facebookLoginButton;11 twitterButton = Application.loginForm.show().twitterLoginButton;12 });13 afterEach(function() {14 window.FB = fb;15 });16 it("assigns the class based on the service name", function() {17 expect(facebookButton).toHaveClass('facebook');18 expect(twitterButton).toHaveClass('twitter');19 expect(facebookButton).toHaveClass('disabled');20 expect(twitterButton).toHaveClass('disabled');21 });22 describe("#attach", function() {23 it("shows the spinner and says Loading (Service)", function() {24 expect(facebookButton.text()).toBe("Loading Facebook");25 expect(twitterButton.text()).toBe("Loading Twitter");26 expect(facebookButton.spinner).toBeVisible();27 expect(twitterButton.spinner).toBeVisible();28 });29 });30 describe("when the service javascript is loaded", function() {31 it("hides the spinner, removes the .disabled class and says 'Sign In With (Service)'", function() {32 Application.facebookInitialized();33 expect(facebookButton.text()).toBe("Sign In With Facebook");34 expect(facebookButton.spinner).toBeHidden();35 expect(facebookButton).not.toHaveClass('disabled');36 Application.twitterInitialized();37 expect(twitterButton.text()).toBe("Sign In With Twitter");38 expect(twitterButton.spinner).toBeHidden();39 expect(twitterButton).not.toHaveClass('disabled');40 });41 });...
Sidebar.js
Source:Sidebar.js
1// @flow strict2import React from "react";3import { useSiteMetadata } from "../../hooks";4import TwitterButton from "../TwitterButton/TwitterButton";5import Author from "./Author";6import Contacts from "./Contacts";7import Menu from "./Menu";8import styles from "./Sidebar.module.scss";9type Props = {10 isIndex?: boolean,11};12const Sidebar = ({ isIndex }: Props) => {13 const { author, copyright, menu } = useSiteMetadata();14 return (15 <div className={styles["sidebar"]}>16 <div className={styles["sidebar__inner"]}>17 <Author author={author} isIndex={isIndex} />18 <Menu menu={menu} />19 <Contacts contacts={author.contacts} />20 <TwitterButton />21 </div>22 </div>23 );24};...
Footer.js
Source:Footer.js
1import React from 'react';2import TwitterButton from './../TwitterButton/TwitterButton.js';3const Footer = ({year}) => (4 <footer className="footer container">5 <p>6 ©{year} <a href="http://labs.topheman.com/">labs.topheman.com</a> - Christophe Rosset<br/>7 <TwitterButton/>8 </p>9 </footer>10);11Footer.propTypes = {12 year: React.PropTypes.number.isRequired13};...
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.
|<p>it('check_object_of_Car', () => {</p><p>
expect(newCar()).toBeInstanceOf(Car);</p><p>
});</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!