Best JavaScript code snippet using jest
bandwidth_test.js
Source: bandwidth_test.js
...64 if (now - lastBitrateMeasureTime >= 1000) {65 var bitrate = (receivedPayloadBytes - lastReceivedPayloadBytes) /66 (now - lastBitrateMeasureTime);67 bitrate = Math.round(bitrate * 1000 * 8) / 1000;68 reportSuccess('Transmitting at ' + bitrate + ' kbps.');69 lastReceivedPayloadBytes = receivedPayloadBytes;70 lastBitrateMeasureTime = now;71 }72 if (stopSending && sentPayloadBytes === receivedPayloadBytes) {73 call.close();74 var elapsedTime = Math.round((now - startTime) * 10) / 10000.0;75 var receivedKBits = receivedPayloadBytes * 8 / 1000;76 reportSuccess('Total transmitted: ' + receivedKBits + ' kilo-bits in ' +77 elapsedTime + ' seconds.');78 testFinished();79 }80 }81}82// Measures video bandwidth estimation performance by doing a loopback call via83// relay candidates for 40 seconds. Computes rtt and bandwidth estimation84// average and maximum as well as time to ramp up (defined as reaching 75% of85// the max bitrate. It reports infinite time to ramp up if never reaches it.86addTest('Connectivity', 'Video bandwidth',87 Call.asyncCreateTurnConfig.bind(null, testVideoBandwidth, reportFatal));88function testVideoBandwidth(config) {89 var maxVideoBitrateKbps = 2000;90 var durationMs = 40000;91 var statStepMs = 100;92 var bweStats = new StatisticsAggregate(0.75 * maxVideoBitrateKbps * 1000);93 var rttStats = new StatisticsAggregate();94 var startTime;95 var call = new Call(config);96 call.setIceCandidateFilter(Call.isRelay);97 call.constrainVideoBitrate(maxVideoBitrateKbps);98 // FEC makes it hard to study bandwidth estimation since there seems to be99 // a spike when it is enabled and disabled. Disable it for now. FEC issue100 // tracked on: https://code.google.com/p/webrtc/issues/detail?id=3050101 call.disableVideoFec();102 doGetUserMedia({audio: false, video: true}, gotStream, reportFatal);103 function gotStream(stream) {104 call.pc1.addStream(stream);105 call.establishConnection();106 startTime = new Date();107 setTimeout(gatherStats, statStepMs);108 }109 function gatherStats() {110 var now = new Date();111 if (now - startTime > durationMs) {112 setTestProgress(100);113 completed();114 } else {115 setTestProgress((now - startTime) * 100 / durationMs);116 call.pc1.getStats(gotStats);117 }118 }119 function gotStats(response) {120 for (var index in response.result()) {121 var report = response.result()[index];122 if (report.id === 'bweforvideo') {123 bweStats.add(Date.parse(report.timestamp),124 parseInt(report.stat('googAvailableSendBandwidth')));125 } else if (report.type === 'ssrc') {126 rttStats.add(Date.parse(report.timestamp),127 parseInt(report.stat('googRtt')));128 }129 }130 setTimeout(gatherStats, statStepMs);131 }132 function completed() {133 call.pc1.getLocalStreams()[0].getVideoTracks()[0].stop();134 call.close();135 reportSuccess('RTT average: ' + rttStats.getAverage() + ' ms');136 reportSuccess('RTT max: ' + rttStats.getMax() + ' ms');137 reportSuccess('Send bandwidth estimate average: ' + bweStats.getAverage() +138 ' bps');139 reportSuccess('Send bandwidth estimate max: ' + bweStats.getMax() + ' bps');140 reportSuccess('Send bandwidth ramp-up time: ' + bweStats.getRampUpTime() +141 ' ms');142 reportSuccess('Test finished');143 testFinished();144 }145}146addExplicitTest('Connectivity', 'Network latency',147 Call.asyncCreateTurnConfig.bind(null, testForWiFiPeriodicScan.bind(null,148 Call.isNotHostCandidate), reportFatal));149addExplicitTest('Connectivity', 'Network latency - Relay',150 Call.asyncCreateTurnConfig.bind(null, testForWiFiPeriodicScan.bind(null,151 Call.isRelay), reportFatal));152function testForWiFiPeriodicScan(candidateFilter, config) {153 var testDurationMs = 5 * 60 * 1000;154 var sendIntervalMs = 100;155 var running = true;156 var delays = [];157 var recvTimeStamps = [];158 var call = new Call(config);159 var chart = createLineChart();160 call.setIceCandidateFilter(candidateFilter);161 var senderChannel = call.pc1.createDataChannel({ordered: false,162 maxRetransmits: 0});163 senderChannel.addEventListener('open', send);164 call.pc2.addEventListener('datachannel', onReceiverChannel);165 call.establishConnection();166 setTimeoutWithProgressBar(finishTest, testDurationMs);167 function onReceiverChannel(event) {168 event.channel.addEventListener('message', receive);169 }170 function send() {171 if (!running) { return; }172 senderChannel.send('' + Date.now());173 setTimeout(send, sendIntervalMs);174 }175 function receive(event) {176 if (!running) { return; }177 var sendTime = parseInt(event.data);178 var delay = Date.now() - sendTime;179 recvTimeStamps.push(sendTime);180 delays.push(delay);181 chart.addDatapoint(sendTime + delay, delay);182 }183 function finishTest() {184 report.traceEventInstant('periodic-delay', {delays: delays,185 recvTimeStamps: recvTimeStamps});186 running = false;187 call.close();188 chart.parentElement.removeChild(chart);189 var avg = arrayAverage(delays);190 var max = arrayMax(delays);191 var min = arrayMin(delays);192 reportInfo('Average delay: ' + avg + ' ms.');193 reportInfo('Min delay: ' + min + ' ms.');194 reportInfo('Max delay: ' + max + ' ms.');195 if (delays.length < 0.8 * testDurationMs / sendIntervalMs) {196 reportError('Not enough samples gathered. Keep the page on the ' +197 'foreground while the test is running.');198 } else {199 reportSuccess('Collected ' + delays.length + ' delay samples.');200 }201 if (max > (min + 100) * 2) {202 reportError('There is a big difference between the min and max delay ' +203 'of packets. Your network appears unstable.');204 }205 testFinished();206 }...
flexigrid-edit.js
Source: flexigrid-edit.js
1$(function () {2 $('input[type=text], textarea').keyup(function () {3 $(this).val($(this).val().toUpperCase());4 });5 $('input[type=text], textarea').each(function () {6 $(this).val($(this).val().toUpperCase());7 });8 var save_and_close = false;9 $('.ptogtitle').click(function () {10 let boxCrud = $(this).closest('div.crud-form')[0];11 let form = $(boxCrud).find('form')[0];12 if ($(this).hasClass('vsble')) {13 $(this).removeClass('vsble');14 $(form).slideDown("slow");15 }16 else {17 $(this).addClass('vsble');18 $(form).slideUp("slow");19 }20 });21 $('.save-and-go-back-button').click(function () {22 save_and_close = true;23 let form = $(this).closest('form')[0];24 $(form).trigger('submit');25 });26 $('.crud-form').submit(function () {27 let my_crud_form = $(this);28 let formId = '#' + $(this).attr('id');29 let btnSaveAndBack = $(this).find('.save-and-go-back-button')[0];30 let reportSuccess = $(this).find('.report-success')[0];31 let reportError = $(this).find('.report-error')[0];32 let formLoading = $(this).find('.form-loading')[0];33 let e = this;34 $(this).ajaxSubmit({35 url: validation_url,36 dataType: 'json',37 cache: 'false',38 beforeSend: function () {39 $(formLoading).show();40 },41 success: function (data) {42 if (data.success) {43 if (confirmation_url == "") {44 doSubmit(data, my_crud_form, formId, formLoading, btnSaveAndBack, reportSuccess, reportError);45 } else {46 $(e).ajaxSubmit({47 url: confirmation_url + '/' + row_id,48 dataType: 'json',49 cache: 'false',50 beforeSend: function () {51 },52 success: function (confirmResponse) {53 if (confirmResponse.success) {54 doSubmit(data, my_crud_form, formId, formLoading, btnSaveAndBack, reportSuccess, reportError);55 } else {56 bootbox.confirm(confirmResponse.message, function (result) {57 if (result) {58 doSubmit(data, my_crud_form, formId, formLoading, btnSaveAndBack, reportSuccess, reportError);59 } else {60 $('#report-error').slideUp('fast');61 $('input').removeClass('field_error');62 }63 });64 }65 },66 error: function () {67 }68 });69 }70 }71 else {72 $('.field_error').each(function () {73 $(this).removeClass('field_error');74 });75 $(reportError).slideUp('fast');76 $(reportError).html(data.error_message);77 $.each(data.error_fields, function (index, value) {78 $('input[name=' + index + ']').addClass('field_error');79 });80 $(reportError).slideDown('normal');81 $(reportSuccess).slideUp('fast').html('');82 }83 },84 error: function () {85 alert(message_update_error);86 $(formLoading).hide();87 }88 });89 return false;90 });91 function doSubmit(data, my_crud_form, formId, formLoading, btnSaveAndBack, reportSuccess, reportError) {92 $(formId).ajaxSubmit({93 dataType: 'text',94 cache: 'false',95 beforeSend: function () {96 $(formLoading).show();97 },98 success: function (result) {99 $(formLoading).fadeOut("slow");100 data = $.parseJSON(result);101 if (data.success) {102 var data_unique_hash = my_crud_form.closest(".flexigrid").attr("data-unique-hash");103 $('.flexigrid[data-unique-hash=' + data_unique_hash + ']').find('.ajax_refresh_and_loading').trigger('click');104 if (save_and_close) {105 if ($(btnSaveAndBack).closest('.ui-dialog').length === 0) {106 window.location = data.success_list_url;107 } else {108 $(".ui-dialog-content").dialog("close");109 success_message(reportSuccess, reportError, data.success_message);110 }111 return true;112 }113 form_success_message(reportSuccess, reportError, data.success_message);114 }115 else {116 form_error_message(reportSuccess, reportError, message_update_error);117 }118 },119 error: function () {120 form_error_message(reportSuccess, reportError, message_update_error);121 }122 });123 }124 if ($('#cancel-button').closest('.ui-dialog').length === 0) {125 $('#cancel-button').click(function () {126 window.location = list_url;127 return false;128 });129 }...
memberProfileSagas.js
Source: memberProfileSagas.js
...32function* markCurrentMemberAsFavorite({memberId}) {33 yield reportPending(MARK_AS_FAVORITE_REQUEST);34 yield call(memberProfileApi.markCurrentMemberAsFavorite, memberId);35 yield dispatchSuccess(MARK_AS_FAVORITE_REQUEST, memberId);36 yield reportSuccess(MARK_AS_FAVORITE_REQUEST);37 yield put(viewersFavoriteActions.fetchProfileRequest('favorites'));38}39function* unmarkCurrentMemberAsFavorite({memberId}) {40 yield reportPending(UNMARK_AS_FAVORITE_REQUEST);41 yield call(memberProfileApi.unmarkCurrentMemberAsFavorite, memberId)42 yield dispatchSuccess(UNMARK_AS_FAVORITE_REQUEST, memberId);43 yield reportSuccess(UNMARK_AS_FAVORITE_REQUEST);44 yield put(viewersFavoriteActions.fetchProfileRequest('favorites'));45}46function* blockUser({memberId}) {47 yield reportPending(BLOCK_USER);48 yield call(memberProfileApi.blockUserAPI, memberId);49 const { data } = yield call(accountSettingApi.fetchBlockedUsersAPI);50 yield put(accountSettingActions.fetchBlockedUsersSuccess(data));51 yield reportSuccess(BLOCK_USER);52}53function* reportUser({payload}) {54 yield reportPending(REPORT_USER);55 yield call(memberProfileApi.reportUserAPI, payload);56 yield reportSuccess(REPORT_USER);57}58function* sendIceBreaker({payload}) {59 yield reportPending(SEND_ICE_BREAKER);60 const {error} = yield call(memberProfileApi.sendIceBreakerAPI, payload);61 if (error === 403) {62 yield put(accountSettingActions.accountUpgradeRequiredRequest({upgrade_required: true}));63 }64 yield reportSuccess(SEND_ICE_BREAKER);65}66function* markCurrentMemberAsFavoriteWatcher() {67 yield takeEvery(MARK_AS_FAVORITE_REQUEST, markCurrentMemberAsFavorite);68}69function* unmarkCurrentMemberAsFavoriteWatcher() {70 yield takeEvery(UNMARK_AS_FAVORITE_REQUEST, unmarkCurrentMemberAsFavorite);71}72function* blockUserWatcher() {73 yield takeEvery(BLOCK_USER, blockUser);74}75function* reportUserWatcher() {76 yield takeEvery(REPORT_USER, reportUser);77}78function* sendIceBreakerWatcher() {...
administration.js
Source: administration.js
...18 if (!validateNewUserCredentials()) return;19 $.post('/password/createaccount', $('#new-account').serializeArray())20 .done(function() {21 resetNewUserCredentials();22 reportSuccess('A new account has been created!');23 })24 .fail(reportError);25}26function logInAs() {27 $.post('/password/loginas', $('#loginas-account').serializeArray())28 .done(function() {29 reportSuccess('You are now logged in as this user');30 })31 .fail(reportError);32}33function validateNewUserCredentials() {34 if (! emailIsValid($('#newaccmail').val())) {35 $('#newaccmail').parent().addClass('has-error');36 reportError('Valid email address must be provided!');37 return false;38 }39 if ($('#password').val().length < 6) {40 $('#password').parent().addClass('has-error');41 reportError('Password was too short!');42 return false;43 }44 $('#newaccmail').parent().removeClass('has-error');45 $('#password').parent().removeClass('has-error');46 hideMessage();47 return true;48}49function resetNewUserCredentials() {50 $('#newaccmail').val('');51 $('#password').val('');52}53function populateAccountsList() {54 $('#list-accounts').empty();55 $.getJSON("/password/accountslist")56 .done(function(data) {57 $('#list-accounts').append('<table class="table table-striped"></table>');58 $('#list-accounts table').append('<tr><th>User</th><th>Delete</th><th>Is admin?</th></tr>');59 $.each(data, function(i, entry){60 var id = entry.id.email;61 var isAdmin = entry.isAdmin;62 var editAdmin = isAdmin63 ? '<input type="checkbox" onClick="unmakeAdmin(\'' + id + '\')" checked />'64 : '<input type="checkbox" onClick="makeAdmin(\'' + id + '\')" />';65 var deleteButton = '<button class="btn btn-danger" onClick="deleteAccount(\'' + id + '\')"><span class="fas fa-trash"></span></button>';66 $('#list-accounts table').append('<tr><td>' + id + '</td><td>' + deleteButton + '</td><td>' + editAdmin + '</td></tr>');67 });68 })69 .fail(reportError);70}71function deleteAccount(mail) {72 $.post("/password/deleteaccount", 'mail=' + mail)73 .done(function() {74 reportSuccess(mail + ' has been removed');75 })76 .fail(reportError)77 .always(populateAccountsList);78}79function makeAdmin(mail) {80 $.post("/password/makeadmin", 'mail=' + mail)81 .done(function() {82 reportSuccess(mail + ' is now an administrator');83 })84 .fail(reportError)85 .always(populateAccountsList);86}87function unmakeAdmin(mail) {88 $.post("/password/unmakeadmin", 'mail=' + mail)89 .done(function() {90 reportSuccess(mail + ' is not an administrator any longer');91 })92 .fail(reportError)93 .always(populateAccountsList);...
CreateReport.js
Source: CreateReport.js
1import React, { useState } from "react";2import Body from "./Body";3import styled from "styled-components";4import { Modal } from "antd";5import { theme } from "constants/theme";6import ReportFinished from "./ReportFinished";7import { useTranslation } from "react-i18next";8const { colors, typography } = theme;9const CreateReport = ({10 postId,11 currentPost,12 setCallReport,13 callReport,14 fromPage,15 forModerator,16 inPendingTab,17 changeType,18}) => {19 const post = currentPost || undefined;20 const [reportSuccess, setReportSuccess] = useState(null);21 const closeModal = () => setCallReport(false);22 const { t } = useTranslation();23 const ModalWrapper = styled(Modal)`24 width: 60rem !important;25 height: 318px !important;26 .ant-modal-title {27 font-family: ${typography.font.family.display};28 font-style: normal;29 font-weight: bold;30 font-size: ${typography.size.large};31 line-height: 115%;32 color: ${colors.darkerGray};33 text-align: center;34 }35 .ant-modal-content {36 max-width: 60rem;37 border-radius: 1rem;38 }39 .ant-modal-header {40 border-radius: 1rem;41 }42 .ant-modal-body {43 padding: 1.5rem;44 }45 `;46 const reportTitle = forModerator?.remove47 ? t("moderation.removePostTitle")48 : forModerator?.keep49 ? t("moderation.keepPostTitle")50 : t("moderation.reportPost");51 return (52 <div className="create-report">53 {reportSuccess === null && (54 <ModalWrapper55 footer={null}56 title={reportTitle}57 visible={callReport}58 destroyOnClose={true}59 onCancel={closeModal}60 >61 <Body62 onSuccess={setReportSuccess}63 closeModal={closeModal}64 postId={postId}65 postReportedBy={post?.reportedBy}66 forModerator={forModerator}67 inPendingTab={inPendingTab}68 />69 </ModalWrapper>70 )}71 {reportSuccess !== null && (72 <ReportFinished73 postId={postId}74 reportSuccess={reportSuccess}75 setCallReport={setCallReport}76 fromPage={fromPage}77 forModerator={forModerator}78 changeType={changeType}79 />80 )}81 </div>82 );83};...
socialCards.router.js
Source: socialCards.router.js
1/**2 * Created by rm on 2018/1/12.3 */4const Application = resolve => require(['@/pages/socialCards/application.vue'], resolve);5const ApplicConfirm = resolve => require(['@/pages/socialCards/applicConfirm.vue'], resolve);6const ApplicSuccse = resolve => require(['@/pages/socialCards/applicSuccse.vue'], resolve);7const ApplicSchedule = resolve => require(['@/pages/socialCards/applicSchedule.vue'], resolve);8const ReportLoss = resolve => require(['@/pages/socialCards/reportLoss.vue'], resolve);9const ReportSuccess = resolve => require(['@/pages/socialCards/reportSuccess.vue'], resolve);10const ChangeInfo = resolve => require(['@/pages/socialCards/changeInfo.vue'], resolve);11export default [12 {path: '/application',component: Application,name:'',title:''},13 {path: '/applicConfirm',component: ApplicConfirm,name:'',title:''},14 {path: '/applicSuccse',component: ApplicSuccse,name:'',title:''},15 {path: '/applicSchedule',component: ApplicSchedule,name:'',title:''},16 {path: '/reportLoss',component: ReportLoss,name:'',title:''},17 {path: '/reportSuccess',component: ReportSuccess,name:'',title:''},18 {path: '/changeInfo',component: ChangeInfo,name:'',title:''},...
jquery.noty.config.js
Source: jquery.noty.config.js
1function success_message(success_message)2{3 noty({4 text: success_message,5 type: 'success',6 dismissQueue: true,7 layout: 'top',8 callback: {9 afterShow: function() {10 setTimeout(function(){11 $.noty.closeAll();12 },7000);13 }14 }15 });16}17function error_message(error_message)18{19 noty({20 text: error_message,21 type: 'error',22 layout: 'top',23 dismissQueue: true24 });25}26function form_success_message(reportSuccess, reportError, success_message)27{28 $(reportSuccess).slideUp('fast');29 $(reportSuccess).html(success_message);30 if ($(reportSuccess).closest('.ui-dialog').length !== 0) {31 $('.go-to-edit-form').click(function(){32 fnOpenEditForm($(this));33 return false;34 });35 }36 $(reportSuccess).slideDown('normal');37 $(reportError).slideUp('fast').html('');38}39function form_error_message(reportSuccess, reportError, error_message)40{41 $(reportError).slideUp('fast');42 $(reportError).html(error_message);43 $(reportError).slideDown('normal');44 $(reportSuccess).slideUp('fast').html('');...
background.js
Source: background.js
2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4var inIncognitoContext = chrome.extension.inIncognitoContext;5var message = inIncognitoContext ? "waiting_incognito" : "waiting";6function reportSuccess() {7 chrome.test.sendMessage(message);8}9chrome.browserAction.onClicked.addListener(function() {10 reportSuccess();11});12chrome.bookmarks.onCreated.addListener(function() {13 reportSuccess();...
How to test if a method returns an array of a class in Jest
How do node_modules packages read config files in the project root?
Jest: how to mock console when it is used by a third-party-library?
ERESOLVE unable to resolve dependency tree while installing a pacakge
Testing arguments with toBeCalledWith() in Jest
Is there assertCountEqual equivalent in javascript unittests jest library?
NodeJS: NOT able to set PERCY_TOKEN via package script with start-server-and-test
Jest: How to consume result of jest.genMockFromModule
How To Reset Manual Mocks In Jest
How to move '__mocks__' folder in Jest to /test?
Since Jest tests are runtime tests, they only have access to runtime information. You're trying to use a type, which is compile-time information. TypeScript should already be doing the type aspect of this for you. (More on that in a moment.)
The fact the tests only have access to runtime information has a couple of ramifications:
If it's valid for getAll
to return an empty array (because there aren't any entities to get), the test cannot tell you whether the array would have had Entity
elements in it if it hadn't been empty. All it can tell you is it got an array.
In the non-empty case, you have to check every element of the array to see if it's an Entity
. You've said Entity
is a class, not just a type, so that's possible. I'm not a user of Jest (I should be), but it doesn't seem to have a test specifically for this; it does have toBeTruthy
, though, and we can use every
to tell us if every element is an Entity
:
it('should return an array of Entity class', async () => {
const all = await service.getAll()
expect(all.every(e => e instanceof Entity)).toBeTruthy();
});
Beware, though, that all calls to every
on an empty array return true
, so again, that empty array issue raises its head.
If your Jest tests are written in TypeScript, you can improve on that by ensuring TypeScript tests the compile-time type of getAll
's return value:
it('should return an array of Entity class', async () => {
const all: Entity[] = await service.getAll()
// ^^^^^^^^^^
expect(all.every(e => e instanceof Entity)).toBeTruthy();
});
TypeScript will complain about that assignment at compile time if it's not valid, and Jest will complain at runtime if it sees an array containing a non-Entity
object.
But jonrsharpe has a good point: This test may not be useful vs. testing for specific values that should be there.
Check out the latest blogs from LambdaTest on this topic:
Node js has become one of the most popular frameworks in JavaScript today. Used by millions of developers, to develop thousands of project, node js is being extensively used. The more you develop, the better the testing you require to have a smooth, seamless application. This article shares the best practices for the testing node.in 2019, to deliver a robust web application or website.
Storybook offers a clean-room setting for isolating component testing. No matter how complex a component is, stories make it simple to explore it in all of its permutations. Before we discuss the Storybook testing in any browser, let us try and understand the fundamentals related to the Storybook framework and how it simplifies how we build UI components.
Quality Assurance (QA) is at the point of inflection and it is an exciting time to be in the field of QA as advanced digital technologies are influencing QA practices. As per a press release by Gartner, The encouraging part is that IT and automation will play a major role in transformation as the IT industry will spend close to $3.87 trillion in 2020, up from $3.76 trillion in 2019.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on WebDriverIO Tutorial and Selenium JavaScript Tutorial.
Having a strategy or plan can be the key to unlocking many successes, this is true to most contexts in life whether that be sport, business, education, and much more. The same is true for any company or organisation that delivers software/application solutions to their end users/customers. If you narrow that down even further from Engineering to Agile and then even to Testing or Quality Engineering, then strategy and planning is key at every level.
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!!