Best JavaScript code snippet using jest
thread-integration.test.js
Source: thread-integration.test.js
...13 const mockChild = new EventEmitter();14 mockChild.postMessage = jest.fn();15 return mockChild;16}17function replySuccess(i, result) {18 mockForkedProcesses[i].emit('message', [PARENT_MESSAGE_OK, result]);19}20function assertCallsToChild(childNum, ...calls) {21 expect(mockForkedProcesses[childNum].postMessage).toHaveBeenCalledTimes(22 calls.length + 1,23 );24 calls.forEach(([methodName, ...args], numCall) => {25 expect(26 mockForkedProcesses[childNum].postMessage.mock.calls[numCall + 1][0],27 ).toEqual([CHILD_MESSAGE_CALL, true, methodName, args]);28 });29}30describe('Jest Worker Process Integration', () => {31 beforeEach(() => {32 mockForkedProcesses = [];33 jest.mock('worker_threads', () => {34 const fakeClass = jest.fn(() => {35 const forkedProcess = mockBuildForkedProcess();36 mockForkedProcesses.push(forkedProcess);37 return forkedProcess;38 });39 return {40 Worker: fakeClass,41 __esModule: true,42 };43 });44 Farm = require('../index').default;45 });46 afterEach(() => {47 jest.resetModules();48 });49 it('calls a single method from the worker', async () => {50 const farm = new Farm('/tmp/baz.js', {51 enableWorkerThreads: true,52 exposedMethods: ['foo', 'bar'],53 numWorkers: 4,54 });55 const promise = farm.foo();56 replySuccess(0, 42);57 expect(await promise).toBe(42);58 });59 it('distributes sequential calls across child processes', async () => {60 const farm = new Farm('/tmp/baz.js', {61 enableWorkerThreads: true,62 exposedMethods: ['foo', 'bar'],63 numWorkers: 4,64 });65 // The first call will go to the first child process.66 const promise0 = farm.foo('param-0');67 assertCallsToChild(0, ['foo', 'param-0']);68 replySuccess(0, 'worker-0');69 expect(await promise0).toBe('worker-0');70 // The second call will go to the second child process.71 const promise1 = farm.foo(1);72 assertCallsToChild(1, ['foo', 1]);73 replySuccess(1, 'worker-1');74 expect(await promise1).toBe('worker-1');75 });76 it('distributes concurrent calls across child processes', async () => {77 const farm = new Farm('/tmp/baz.js', {78 enableWorkerThreads: true,79 exposedMethods: ['foo', 'bar'],80 numWorkers: 4,81 });82 // Do 3 calls to the farm in parallel.83 const promise0 = farm.foo('param-0');84 const promise1 = farm.foo('param-1');85 const promise2 = farm.foo('param-2');86 // Check that the method calls are sent to each separate child process.87 assertCallsToChild(0, ['foo', 'param-0']);88 assertCallsToChild(1, ['foo', 'param-1']);89 assertCallsToChild(2, ['foo', 'param-2']);90 // Send different responses from each child.91 replySuccess(0, 'worker-0');92 replySuccess(1, 'worker-1');93 replySuccess(2, 'worker-2');94 // Check95 expect(await promise0).toBe('worker-0');96 expect(await promise1).toBe('worker-1');97 expect(await promise2).toBe('worker-2');98 });99 it('sticks parallel calls to children', async () => {100 const farm = new Farm('/tmp/baz.js', {101 computeWorkerKey: () => '1234567890abcdef',102 enableWorkerThreads: true,103 exposedMethods: ['foo', 'bar'],104 numWorkers: 4,105 });106 // Do 3 calls to the farm in parallel.107 const promise0 = farm.foo('param-0');108 const promise1 = farm.foo('param-1');109 const promise2 = farm.foo('param-2');110 // Send different responses for each call (from the same child).111 replySuccess(0, 'worker-0');112 replySuccess(0, 'worker-1');113 replySuccess(0, 'worker-2');114 // Check that all the calls have been received by the same child).115 assertCallsToChild(116 0,117 ['foo', 'param-0'],118 ['foo', 'param-1'],119 ['foo', 'param-2'],120 );121 // Check that responses are correct.122 expect(await promise0).toBe('worker-0');123 expect(await promise1).toBe('worker-1');124 expect(await promise2).toBe('worker-2');125 });...
process-integration.test.js
Source: process-integration.test.js
...13 const mockChild = new EventEmitter();14 mockChild.send = jest.fn();15 return mockChild;16}17function replySuccess(i, result) {18 mockForkedProcesses[i].emit('message', [PARENT_MESSAGE_OK, result]);19}20function assertCallsToChild(childNum, ...calls) {21 expect(mockForkedProcesses[childNum].send).toHaveBeenCalledTimes(22 calls.length + 1,23 );24 calls.forEach(([methodName, ...args], numCall) => {25 expect(26 mockForkedProcesses[childNum].send.mock.calls[numCall + 1][0],27 ).toEqual([CHILD_MESSAGE_CALL, true, methodName, args]);28 });29}30jest.mock('worker_threads', () => {31 throw Error('Unsupported');32});33describe('Jest Worker Integration', () => {34 beforeEach(() => {35 mockForkedProcesses = [];36 jest.mock('child_process', () => ({37 fork() {38 const forkedProcess = mockBuildForkedProcess();39 mockForkedProcesses.push(forkedProcess);40 return forkedProcess;41 },42 }));43 Farm = require('../index').default;44 });45 afterEach(() => {46 jest.resetModules();47 });48 it('calls a single method from the worker', async () => {49 const farm = new Farm('/tmp/baz.js', {50 exposedMethods: ['foo', 'bar'],51 numWorkers: 4,52 });53 const promise = farm.foo();54 replySuccess(0, 42);55 expect(await promise).toBe(42);56 });57 it('distributes sequential calls across child processes', async () => {58 const farm = new Farm('/tmp/baz.js', {59 exposedMethods: ['foo', 'bar'],60 numWorkers: 4,61 });62 // The first call will go to the first child process.63 const promise0 = farm.foo('param-0');64 assertCallsToChild(0, ['foo', 'param-0']);65 replySuccess(0, 'worker-0');66 expect(await promise0).toBe('worker-0');67 // The second call will go to the second child process.68 const promise1 = farm.foo(1);69 assertCallsToChild(1, ['foo', 1]);70 replySuccess(1, 'worker-1');71 expect(await promise1).toBe('worker-1');72 });73 it('distributes concurrent calls across child processes', async () => {74 const farm = new Farm('/tmp/baz.js', {75 exposedMethods: ['foo', 'bar'],76 numWorkers: 4,77 });78 // Do 3 calls to the farm in parallel.79 const promise0 = farm.foo('param-0');80 const promise1 = farm.foo('param-1');81 const promise2 = farm.foo('param-2');82 // Check that the method calls are sent to each separate child process.83 assertCallsToChild(0, ['foo', 'param-0']);84 assertCallsToChild(1, ['foo', 'param-1']);85 assertCallsToChild(2, ['foo', 'param-2']);86 // Send different responses from each child.87 replySuccess(0, 'worker-0');88 replySuccess(1, 'worker-1');89 replySuccess(2, 'worker-2');90 // Check91 expect(await promise0).toBe('worker-0');92 expect(await promise1).toBe('worker-1');93 expect(await promise2).toBe('worker-2');94 });95 it('sticks parallel calls to children', async () => {96 const farm = new Farm('/tmp/baz.js', {97 computeWorkerKey: () => '1234567890abcdef',98 exposedMethods: ['foo', 'bar'],99 numWorkers: 4,100 });101 // Do 3 calls to the farm in parallel.102 const promise0 = farm.foo('param-0');103 const promise1 = farm.foo('param-1');104 const promise2 = farm.foo('param-2');105 // Send different responses for each call (from the same child).106 replySuccess(0, 'worker-0');107 replySuccess(0, 'worker-1');108 replySuccess(0, 'worker-2');109 // Check that all the calls have been received by the same child).110 assertCallsToChild(111 0,112 ['foo', 'param-0'],113 ['foo', 'param-1'],114 ['foo', 'param-2'],115 );116 // Check that responses are correct.117 expect(await promise0).toBe('worker-0');118 expect(await promise1).toBe('worker-1');119 expect(await promise2).toBe('worker-2');120 });...
index.js
Source: index.js
1import {2 GET_NOTIFICATION_START,3 GET_NOTIFICATION_SUCCESS,4 GET_NOTIFICATION_FAILED,5 GET_NOTIFICATIONS_START,6 GET_NOTIFICATIONS_SUCCESS,7 GET_NOTIFICATIONS_FAILED,8 DELETE_NOTIFICATION_START,9 DELETE_NOTIFICATION_SUCCESS,10 DELETE_NOTIFICATION_FAILED,11 VIEW_STATUS_START,12 VIEW_STATUS_SUCCESS,13 VIEW_STATUS_FAILED,14 REPLY_START,15 REPLY_SUCCESS,16 REPLY_FAILED,17} from "../../actions/notification";18const initialState = {19 notifications: [],20 notification: {},21 getNotificationLoading: false,22 getNotificationSuccess: false,23 getNotificationsLoading: false,24 deleteNotificationLoading: false,25 deleteNotificationSuccess: false,26 replyLoading: false,27 replySuccess: false,28 viewStatusLoading: false,29 viewStatusSuccess: false,30 error: ""31}32export const notificationReducer = (state=initialState, action) => {33 switch(action.type) {34 case GET_NOTIFICATION_START:35 return {36 ...state,37 getNotificationLoading: true,38 }39 case GET_NOTIFICATION_SUCCESS:40 return {41 ...state,42 getNotificationLoading: false,43 getNotificationSuccess: true,44 notification: action.data,45 }46 case GET_NOTIFICATION_FAILED:47 return {48 ...state,49 getNotificationLoading: false,50 getNotificationSuccess: false,51 error: action.error52 }53 case GET_NOTIFICATIONS_START:54 return {55 ...state,56 getNotificationsLoading: true57 }58 case GET_NOTIFICATIONS_SUCCESS:59 return {60 ...state,61 getNotificationsLoading: false,62 getNotificationsSuccess: true,63 notifications: action.data,64 }65 case GET_NOTIFICATIONS_FAILED:66 return {67 ...state,68 getNotificationsLoading: false,69 getNotificationsSuccess: false,70 error: action.error71 }72 case DELETE_NOTIFICATION_START:73 return {74 ...state,75 deleteNotificationLoading: true76 }77 case DELETE_NOTIFICATION_SUCCESS:78 return {79 ...state,80 deleteNotificationLoading: false,81 deleteNotificationSuccess: true,82 notification: action.data,83 }84 case DELETE_NOTIFICATION_FAILED:85 return {86 ...state,87 deleteNotificationLoading: false,88 deleteNotificationSuccess: false,89 error: action.error90 }91 case VIEW_STATUS_START:92 return {93 ...state,94 viewStatusLoading: true,95 }96 case VIEW_STATUS_SUCCESS:97 return {98 ...state,99 viewStatusLoading: false,100 viewStatusSuccess: true,101 // notification: action.data,102 }103 case VIEW_STATUS_FAILED:104 return {105 ...state,106 replyLoading: false,107 replySuccess: false,108 error: action.error109 }110 case REPLY_START:111 return {112 ...state,113 replyLoading: true,114 }115 case REPLY_SUCCESS:116 return {117 ...state,118 replyLoading: false,119 replySuccess: true,120 notification: action.data,121 }122 case REPLY_FAILED:123 return {124 ...state,125 replyLoading: false,126 replySuccess: false,127 error: action.error128 }129 default:130 return state;131 }...
comments.js
Source: comments.js
...19 state.msg = undefined;20 return state;21 })22 }23 replySuccess(){24 this.setState((prevState, props) => {25 var state = prevState;26 state.index = state.index + 1;27 state.msg = window.getString('postSuccess')28 return state;29 })30 }31 render(){32 var that = this;33 var commentDivs = this.props.comments.map(function(comment,i) {34 var tag = ""35 var msg = ""36 if(i === that.state.index && that.state.msg){37 msg = <div className="msg">{that.state.msg}</div>...
ReplyContainer.js
Source: ReplyContainer.js
1import React, { useEffect } from 'react';2import ReplyForm from '../../components/reply/ReplyForm'3import { useDispatch, useSelector } from 'react-redux';4import { changeField, initForm, registerReply } from '../../modules/reply';5import { getComment } from '../../modules/comment';6import { withRouter } from 'react-router';7const ReplyContainer = ({ match }) => {8 const { commentId } = match.params;9 const user = JSON.parse(localStorage.getItem('user'));10 const dispatch = useDispatch();11 const { reply, replySuccess, replyError, comment, loading } = useSelector(({ reply, comment }) => ({12 reply: reply.reply,13 replySuccess: reply.replySuccess,14 replyError: reply.replyError,15 comment: comment.comment,16 loading: comment.loading17 }))18 const onChange = e => {19 const { name, value } = e.target;20 dispatch(changeField({21 key: name,22 value23 }))24 }25 const onSubmit = e => {26 e.preventDefault();27 if (reply.replyContent === "") return alert('ëê¸ì ì
ë ¥í´ì£¼ì¸ì');28 dispatch(registerReply({29 replyContent: reply.replyContent,30 user: user._id,31 comment: commentId32 }))33 }34 useEffect(() => {35 dispatch(initForm());36 }, [dispatch])37 useEffect(() => {38 if (replySuccess) {39 dispatch(getComment({ commentId }))40 dispatch(initForm());41 }42 if (replyError) {43 console.log(replyError)44 }45 }, [replyError, replySuccess, dispatch, commentId])46 return (47 <ReplyForm48 onSubmit={onSubmit}49 onChange={onChange}50 reply={reply}51 comment={comment}52 loading={loading}53 />54 );55};...
name.js
Source: name.js
1// kiwi/relva/commands/name.js - Created March 16th, 20182const { opUser, guild } = require('../index');3module.exports = {4 name: 'name',5 aliases: ['username'],6 description: 'Sets the KIWI username and of a Discord user.',7 messages: {8 replyInvalidArgs: 'you must specify a username to change to like so: `!name KIWIBot`',9 replySuccess: 'you\'ll now be known as such.',10 replyDumbass: 'that\'s already your username...',11 },12 execute(message, args, privLevel) {13 if(!args.length) {14 this.die(message, this.messages.replyInvalidArgs);15 return;16 }17 if(args[0] === message.author.nickname) {18 this.die(message, this.messages.replyDumbass);19 return;20 }21 // WARNING: Hacky re-use of old code :<22 opUser.setUsername(message.author.id, args[0]).then(resp => {23 if (resp.includes('#kiwipugs')) {24 // Ensure weirdo Administrator perm breaking doesn't happen when renaming25 if(privLevel != 3) {26 // Set username immediately27 opUser.usernameAssoc(message.author, guild);28 }29 // Success30 this.die(message, this.messages.replySuccess);31 return;32 }33 // Invalid or taken username34 this.die(message, resp);35 });36 },37 die(message, resp) {38 message.reply(resp);39 message.channel.stopTyping();40 return;41 },...
topicReducer.js
Source: topicReducer.js
1/**2 * Created by liujia on 2015/12/8.3 */4var types = require('../actions/ActionTypes')5var initialState = {6 upSuccess:false,7 replySuccess:false,8 publishSuccess:false9}10export default function configReducer(state = initialState, action={}) {11 switch (action.type) {12 case types.UP_COMMENT_SUCCESS:13 return {14 ...state,15 upSuccess:true16 }17 case types.UP_COMMENT_FAILED:18 return {19 ...state,20 upSuccess:false21 }22 case types.REPLY_SUCCESS:23 return {24 ...state,25 replySuccess:true26 }27 case types.REPLY_SET_FALSE:28 return {29 ...state,30 replySuccess:false31 }32 case types.PUBLISH_SUCCESS:33 return {34 ...state,35 publishSuccess:true36 }37 case types.PUBLISH_SET_FALSE:38 return {39 ...state,40 publishSuccess:false41 }42 default :43 return state44 }...
ReplySuccess.js
Source: ReplySuccess.js
1import PropTypes from "prop-types";2import React from "react";3import FormSuccess from "@agir/voting_proxies/Common/FormSuccess";4import Spacer from "@agir/front/genericComponents/Spacer";5const ReplySuccess = ({ isAvailable }) => (6 <FormSuccess>7 <h2>Demande enregistrée</h2>8 <Spacer size="0.875rem" />9 {isAvailable ? (10 <p>11 Nous vous recontacterons dès que l'établissement de la procuration aura12 été confirmée.13 </p>14 ) : (15 <p>16 Votre indisponibilité pour prendre une procuration de vote a bien été17 enregistrée.18 </p>19 )}20 <Spacer size="0.875rem" />21 <p>Merci de votre engagement !</p>22 </FormSuccess>23);24ReplySuccess.propTypes = {25 isAvailable: PropTypes.bool.isRequired,26};...
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!!