Best JavaScript code snippet using best
kafkaThrottlingManager-test.js
Source:kafkaThrottlingManager-test.js
...45 partition: 4,46 msg: 'some-message1',47 offset: 100048 };49 kafkaThrottlingManager.handleIncomingMessage(message);50 await sleep(1000);51 should(commitFunctionStub.calledOnce).eql(true);52 should(logTraceStub.args[0][0]).equal(`kafkaThrottlingManager finished handling message: topic: ${message.topic}, partition: ${message.partition}, offset: ${message.offset}`);53 });54 it('Second call to handleIncomingMessage should write to inner queue ', async () => {55 sandbox.resetHistory();56 let message = {57 topic: 'TopicA',58 partition: 4,59 msg: 'some-message2',60 offset: 100261 };62 kafkaThrottlingManager.handleIncomingMessage(message);63 await sleep(100);64 should(commitFunctionStub.calledOnce).eql(true);65 should(logTraceStub.args[0][0]).equal(`kafkaThrottlingManager finished handling message: topic: ${message.topic}, partition: ${message.partition}, offset: ${message.offset}`);66 });67 });68 describe('handleIncomingMessage is failing', () => {69 let errorCallbackStub;70 before(async () => {71 logInfoStub = sandbox.stub();72 logTraceStub = sandbox.stub();73 logErrorStub = sandbox.stub();74 errorCallbackStub = sandbox.stub();75 logger = { error: logErrorStub, trace: logTraceStub, info: logInfoStub };76 commitFunctionStub = sandbox.stub();77 kafkaStreamConsumer.commit = commitFunctionStub;78 kafkaThrottlingManager = new KafkaThrottlingManager();79 kafkaThrottlingManager.init(1, 5000, ['TopicA', 'TopicB'],80 () => Promise.reject(new Error('some error message')),81 (msg, err) => {82 return errorCallbackStub(msg, err);83 },84 kafkaStreamConsumer, logger);85 });86 afterEach(() => {87 sandbox.reset();88 });89 after(() => {90 kafkaThrottlingManager.stop();91 sandbox.restore();92 });93 it('handleIncomingMessage should rejected and write it to log ', async () => {94 sandbox.resetHistory();95 errorCallbackStub.yields('error function that resolves');96 let message = {97 topic: 'TopicA',98 partition: 4,99 msg: 'some-message',100 offset: 1005101 };102 let endStub = sandbox.stub();103 let histogram = {104 startTimer: sandbox.stub()105 };106 histogram.startTimer.returns(endStub);107 kafkaThrottlingManager.handleIncomingMessage(message, histogram);108 await sleep(100);109 should(commitFunctionStub.calledOnce).eql(true);110 should(errorCallbackStub.calledOnce).eql(true);111 should(errorCallbackStub.args[0][0]).deepEqual(message);112 should(errorCallbackStub.args[0][1]).deepEqual(new Error('some error message'));113 should(logErrorStub.args[0]).eql(['MessageFunction was rejected', new Error('some error message')]);114 });115 it('handleIncomingMessage should rejected and write it to log ', async () => {116 sandbox.resetHistory();117 errorCallbackStub.rejects('error function that rejects');118 let message = {119 topic: 'TopicA',120 partition: 4,121 msg: 'some-message',122 offset: 1005123 };124 let endStub = sandbox.stub();125 let histogram = {126 startTimer: sandbox.stub()127 };128 histogram.startTimer.returns(endStub);129 kafkaThrottlingManager.handleIncomingMessage(message, histogram);130 await sleep(100);131 should(commitFunctionStub.calledOnce).eql(true);132 should(errorCallbackStub.calledOnce).eql(true);133 should(errorCallbackStub.args[0][0]).deepEqual(message);134 should(logErrorStub.args[0]).eql(['MessageFunction was rejected', new Error('some error message')]);135 should(logErrorStub.args[1][0]).eql('ErrorMessageFunction invocation was rejected');136 });137 });138 describe('Testing init and the manageQueue by interval', () => {139 let interval = 1000;140 let thresholdMessages = 20;141 let callbackFunc = () => {142 return new Promise((resolve, reject) => {143 setTimeout(() => {144 return resolve();145 }, 200);146 });147 };148 let callbackErrorFunc = () => {149 return new Promise((resolve, reject) => {150 setTimeout(() => {151 return resolve();152 }, 200);153 });154 };155 before(() => {156 logInfoStub = sandbox.stub();157 logTraceStub = sandbox.stub();158 logger = { error: sandbox.stub(), trace: logTraceStub, info: logInfoStub };159 });160 after(() => {161 kafkaThrottlingManager.stop();162 sandbox.resetHistory();163 sandbox.restore();164 });165 it('Successful init to inner async queues', () => {166 kafkaThrottlingManager = new KafkaThrottlingManager();167 kafkaThrottlingManager.init(thresholdMessages,168 interval, ['TopicA', 'TopicB'], callbackFunc, callbackErrorFunc, kafkaStreamConsumer, logger);169 let queues = kafkaThrottlingManager.innerQueues;170 queues.should.eql({ TopicA: {}, TopicB: {} });171 });172 it('Wait for first interval', (done) => {173 setTimeout(() => done(), interval);174 });175 it('Verify manageQueues was called and not paused', () => {176 should(logTraceStub.args[0][0]).eql('managing queues..');177 should(logTraceStub.args[1][0]).eql('Total messages in queues are: 0');178 should(consumerSetThirstyStub.args[0][0]).eql(true);179 should(consumerResumeStub.calledOnce).eql(true);180 should(consumerPauseStub.callCount).eql(0);181 sandbox.reset();182 });183 it('set number of messages to above the threshold', () => {184 for (let i = 0; i < thresholdMessages + 30; i++) {185 kafkaThrottlingManager.handleIncomingMessage({ partition: 0, topic: 'TopicA', offset: i });186 }187 });188 it('Wait for second interval', (done) => {189 setTimeout(() => done(), interval);190 });191 it('Verify manageQueues was called and paused', () => {192 should(consumerSetThirstyStub.args[consumerSetThirstyStub.args.length - 1][0]).eql(false);193 should(consumerPauseStub.calledOnce).eql(true);194 });195 });...
ChatRoom.jsx
Source:ChatRoom.jsx
1import { useEffect, useState, useRef } from 'react'2import Button from 'react-bootstrap/Button'3import Form from 'react-bootstrap/Form'4import InputGroup from 'react-bootstrap/InputGroup'5import ListGroup from 'react-bootstrap/ListGroup'6import { useNavigate, useParams } from 'react-router-dom'7import { useChatContext } from '../contexts/ChatContextProvider'8const ChatRoom = () => {9 const [message, setMessage] = useState('')10 const [messages, setMessages] = useState([])11 const [users, setUsers] = useState([])12 const [connected, setConnected] = useState(false)13 const { chatUsername, socket } = useChatContext()14 const { room_id } = useParams()15 const navigate = useNavigate()16 const messageRef = useRef()17 const handleIncomingMessage = msg => {18 console.log("Received a new chat message", msg)19 // add message to chat20 setMessages(prevMessages => [ ...prevMessages, msg ])21 }22 const handleUpdateUsers = userlist => {23 console.log("Got new userlist", userlist)24 setUsers(userlist)25 }26 const handleSubmit = async e => {27 e.preventDefault()28 if (!message.length) {29 return30 }31 // construct message object32 const msg = {33 username: chatUsername,34 room: room_id,35 content: message,36 timestamp: Date.now(),37 }38 // emit chat message39 socket.emit('chat:message', msg)40 // add message to chat41 setMessages(prevMessages =>42 [43 ...prevMessages,44 { ...msg, self: true }45 ]46 )47 // clear message input and refocus on input element48 setMessage('')49 messageRef.current.focus()50 }51 // connect to room when component is mounted52 useEffect(() => {53 // if no username, redirect them to the login page54 if (!chatUsername) {55 navigate('/')56 return57 }58 // emit join request59 socket.emit('user:joined', chatUsername, room_id, status => {60 console.log(`Successfully joined ${room_id} as ${chatUsername}`, status)61 setConnected(true)62 })63 // listen for incoming messages64 socket.on('chat:message', handleIncomingMessage)65 // listen for updated userlist66 socket.on('user:list', handleUpdateUsers)67 return () => {68 console.log("Running cleanup")69 // stop listening to events70 socket.off('chat:message', handleIncomingMessage)71 socket.off('user:list', handleUpdateUsers)72 // rage-quit73 socket.emit('user:left', chatUsername, room_id)74 }75 }, [socket, room_id, chatUsername, navigate])76 useEffect(() => {77 // focus on message input78 messageRef.current && messageRef.current.focus()79 }, [])80 // display connecting message81 if (!connected) {82 return (83 <p>Stand by, connecting....</p>84 )85 }86 return (87 <div id="chat-room">88 <div id="chat">89 <h2>#{room_id}</h2>90 <div id="messages-wrapper">91 <ListGroup id="messages">92 {messages.map((message, index) => {93 const ts = new Date(message.timestamp)94 const time = ts.toLocaleTimeString()95 return (96 <ListGroup.Item key={index} className="message">97 <span className="time">{time}</span>98 <span className="user">{message.username}:</span>99 <span className="content">{message.content}</span>100 </ListGroup.Item>101 )102 }103 )}104 </ListGroup>105 </div>106 <Form onSubmit={handleSubmit} id="message-form">107 <InputGroup>108 <Form.Control109 onChange={e => setMessage(e.target.value)}110 placeholder="Say something nice..."111 ref={messageRef}112 required113 type="text"114 value={message}115 />116 <Button variant="success" type="submit" disabled={!message.length}>Send</Button>117 </InputGroup>118 </Form>119 </div>120 <div id="users">121 <h2>Users</h2>122 <ul id="online-users">123 {Object.values(users).map((user, index) =>124 <li key={index}><span className="user-icon">ð§</span> {user}</li>125 )}126 </ul>127 </div>128 </div>129 )130}...
App.js
Source:App.js
...22 socket.emit(JOIN_ROOM, {23 room: 'room_name',24 id: USER_ID,25 })26 handleIncomingMessage({ message: `Hi, ${USER_ID}.` })27 }28 const handleUserConnect = (userId) => {29 handleIncomingMessage({ message: `${userId} connected` })30 }31 const handleUserDisconnect = (userId) => {32 handleIncomingMessage({ message: `${userId} disconnected` })33 }34 const addSocketListeners = () => {35 socket.on(RECEIVE_MESSAGE, handleIncomingMessage)36 socket.on(USER_CONNECTED, handleUserConnect)37 socket.on(USER_DISCONNECTED, handleUserDisconnect)38 }39 const removeSocketListeners = () => {40 socket.off(RECEIVE_MESSAGE, handleIncomingMessage)41 socket.off(USER_CONNECTED, handleUserConnect)42 socket.off(USER_DISCONNECTED, handleUserDisconnect)43 }44 useEffect(() => {45 joinSocketRoom()46 addSocketListeners()...
Using AI Code Generation
1var BestBot = require('./BestBot');2var myBot = new BestBot();3myBot.handleIncomingMessage('hello');4myBot.handleIncomingMessage('what is your name?');5myBot.handleIncomingMessage('what is 2 + 2?');6myBot.handleIncomingMessage('what is 2 - 2?');7myBot.handleIncomingMessage('what is 2 * 2?');8myBot.handleIncomingMessage('what is 2 / 2?');9myBot.handleIncomingMessage('what is 2 ^ 2?');10myBot.handleIncomingMessage('what is 2 % 2?');11myBot.handleIncomingMessage('what is the square root of 2?');12myBot.handleIncomingMessage('what is 2 + 2 * 2?');13myBot.handleIncomingMessage('what is 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2?');
Using AI Code Generation
1var BestBot = require('./BestBot.js');2var bot = new BestBot();3bot.handleIncomingMessage('Hello', function (response) {4 console.log(response);5});6bot.handleIncomingMessage('How are you', function (response) {
Using AI Code Generation
1const BestBot = require('./BestBot');2let myBot = new BestBot();3myBot.handleIncomingMessage('hello');4myBot.handleIncomingMessage('help');5myBot.handleIncomingMessage('what do you do?');6myBot.handleIncomingMessage('who are you?');7myBot.handleIncomingMessage('what is your name?');8myBot.handleIncomingMessage('goodbye');9myBot.handleIncomingMessage('bye');10myBot.handleIncomingMessage('see you later');11myBot.handleIncomingMessage('I love you');12myBot.handleIncomingMessage('I hate you');13myBot.handleIncomingMessage('I like you');14myBot.handleIncomingMessage('I am happy');15myBot.handleIncomingMessage('I am sad');16myBot.handleIncomingMessage('I am angry');17myBot.handleIncomingMessage('I am confused');18myBot.handleIncomingMessage('I am bored');19myBot.handleIncomingMessage('I am tired');20myBot.handleIncomingMessage('I am hungry');21myBot.handleIncomingMessage('I am thirsty');22myBot.handleIncomingMessage('I am scared');23myBot.handleIncomingMessage('I am excited');24myBot.handleIncomingMessage('I am worried');25myBot.handleIncomingMessage('I am anxious');26myBot.handleIncomingMessage('I am sick');27myBot.handleIncomingMessage('I am not well');28myBot.handleIncomingMessage('I am ill');29myBot.handleIncomingMessage('I am freezing');30myBot.handleIncomingMessage('I am hot');31myBot.handleIncomingMessage('I am cold');32myBot.handleIncomingMessage('I am warm');33myBot.handleIncomingMessage('I am in pain');34myBot.handleIncomingMessage('I am in trouble');35myBot.handleIncomingMessage('I am in danger');36myBot.handleIncomingMessage('I am in distres
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!