Jest mock middleware response
I am trying to mock a middleware response, and i am trying to use jest.spyOn()
but can't seem to get it working
My controller.ts has the following
import someMiddleware from '../someMiddleware;
....
....
this.route.post('/getData', someMiddleware, setValue)
In someMiddlware.ts
//making a fetch call based on data in req.body
.....
const data = await fetchData(url, data)
next()
.....
In my test file controller.test.ts
describe('Test Data', () => {
beforeEach(() => {
someMiddlewareSpyOn = jest.spyOn(meddelware, "someMiddleware");
});
afterEach(() => {
jest.resetModules();
jest.resetAllMocks();
});
it('response status should be a 200', async () => {
someMiddlewareSpyOn.mockResolvedValue({data:[].....});
const res = await request(app.getServer())
.post('/getData');
expect(res.status).toBe(200);
})
});
The above does not work, looking for assistance on how to do this.
See also questions close to this topic
-
How to devise this solution to Non-Constructible Change challenge from Algoexpert.io
I'm working through algoexpert.io coding challenges and I'm having trouble undersatnding the suggested solution to one of the questions titled Non-Constructible Change
Here's the challenge question:
Given an array of positive integers representing the values of coins in your possession, write a function that returns the minimum amount of change (the minimum sum of money) that you cannot create. The given coins can have any positive integer value and aren't necessarily unique (i.e., you can have multiple coins of the same value).
For example, if you're given coins = [1, 2, 5], the minimum amount of change that you can't create is 4. If you're given no coins, the minimum amount of change that you can't create is 1.
// O(nlogn) time, O(n) size. function nonConstructibleChange(coins) { coins = coins.sort((a, b) => a - b); // O(nlogn) time operation let change = 0; for (coin of coins) { if (coin > change + 1) return change + 1; change += coin; } return change + 1; }
My problem
I am not completely sure how did the author of the solution come up with the intuition that
if the current coin is greater than `change + 1`, the smallest impossible change is equal to `change + 1`.
I can see how it tracks, and indeed the algorithm passes all tests, but I'd like to know more about a process I could use to devise this rule.
Thank you for taking the time to read the question!
-
My document is not defined because of lost context
Working with vanilla.js and my code looks like this:
class Restaurant { constructor() { this.menu = []; this.categories = ['all']; } handleSearch(event) { const searchInput = document.querySelector('.search-input'); const minPriceInput = document.querySelector('.min-price'); const maxPriceInput = document.querySelector('.max-price'); if (event.target.matches('.search-btn')) { event.preventDefault(); const keyword = searchInput.value.toLowerCase(); const minPrice = minPriceInput.value || 0; const maxPrice = maxPriceInput || Infinity; let category = docuemnt.querySelector(".filter-active").dataset.id; let filteredMenu = []; if (category === this.categories[0]) { // categories[0] is "all"; filteredMenu = menu.filter(item => { return item.title.includes(keyword) && item.price >= minPrice && item.price <= maxPrice; }) this.renderMenu(filteredMenu); } else { filteredMenu = menu.filter(item => { return item.category === selectedCategory && item.title.includes(keyword) && item.price >= minPrice && item.price <= maxPrice; }) this.renderMenu(filteredMenu); } } } render() { const buttonsContainer = document.querySelector('.btn-container'); const searchButton = document.querySelector('.search-btn'); buttonsContainer.addEventListener('click', this.handleFilter.bind(this)); searchButton.addEventListener('click', this.handleSearch.bind(this)); this.setCategories(); this.renderButtons(); this.renderMenu(this.menu); } }
my document object is undefined inside the handleSearch method. Is it possible to solve this problem without placing all element variables outside the method? Even if I do so I have another variable "categories" which is using document object.
-
React-dnd multiple elements
I can make react-dnd drag easily having a single element to drag over however I have array of 4 fields I'd like to make draggable. In my example code down below it creates four boxes from mapping the array and each box has a className of 'element'. Which should make them all draggable however they won't move.
Here is my drag code:
const ELEMENT = 'element'; const [{ isDragging }, drag, dragPreview] = useDrag(() => ({ type: ELEMENT, collect: (monitor) => ({ isDragging: monitor.isDragging() }) }))
Here is my draggable element:
{FieldDetail.map((e,i) => <div key={i} ref={dragPreview} style={{ opacity: isDragging ? 0.5 : 1}}> <div className='element' ref={drag}></div> </div> )}
Any ideas? Do I need to do something more within the type or className?
-
Make Query With having, count and join in Sequelize
I have two tables in MySQL, joined with a Many to Many relationship. They are as follows:
Equipments:
Field Type Id PK, Integer name Varchar description Varchar createdAt datetime Instructions:
Field Type id FK, integer name Varchar And the table that joins them as a pivot:
EquipmentInstructions:
Field Type equipmentId FK, integer instructionId FK, integer The query I'm trying to do is this, but getting all the fields, not just the name and description.
SELECT P.equipmentId, E.name, E.description FROM EquipmentInstructions P JOIN Equipments E ON P.equipmentId=E.id WHERE P.instructionId IN (1,2,3) GROUP BY P.equipmentId HAVING COUNT(*)=3;
This query returns:
equipmentId, name, description '8', 'ESPATULA', 'Espátula de cocina' '7', 'PARRILLA', 'Para asar la carne' '4', 'CUCHARÓN', 'Cuchara grande'
I am trying to pass said query to Sequelize, so far I have achieved this:
Equipment.findAndCountAll({ include: [ { model: Instruction, as: "instructions", through: { where: { instructionId: { [Op.in]: [1,2,3], }, }, }, attributes: { include: ["id"], }, }, ], group: ["id"], having: Sequelize.where(Sequelize.fn("COUNT", "*"), "=", recipeIds.length), }) .then((result) => { console.log(result); res.json(result); })
The result is correct, however, I only get the id of the equipment:
{ count: [ { id: 4, count: 3 }, { id: 7, count: 3 }, { id: 8, count: 3 } ], rows: [] }
I need to show the complete information of the equipment and additionally count how many records exist in total (by pagination issues).
-
How to ssr Svelte and pass data from express in node js
I am trying svelte and I might use it for my future website, but there is on thing that has stopped me from suing many js frameworks/compilers. It is server side rendering (one reason is I use server-less so it would be easier then prerendering). Is there a way to use express to server-side-render svelte on every request and also pass data from my node js app too so I don't have to make a bunch of other request? For example the App.svelte might be:
<script> export let data let count = 0 </script> <main> <button on:click={count++}>Increase Count BY 1</button> <h1>{data}<h1> </main>
and main.js:
import App from './App.svelte'; const app = new App({ target: document.body, props: { } }); export default app;
I want to get the data value from the server and use it in the svelte code and also sever-side-render it. Is there a way I can do this?
-
how to send long complex array with socket.io?
I have complex an array containing lots of base64 data. and I send this array to server with socket.io. If I send an array containing one or two base64 data. the function is working successfully. but if I send an array containing lots of base64 data. function does not react.
my purpose
- client will prepare templates.
- When the client clicks the save button, it sends this template to the server with socket.io.
- templates sent to the server will be saved to hdd with nodejs.
my array template
const MyArray = [ { div_id:div.id, div_innerhtml:div.innerHTML, //<img src=base64... div_backgroundimage : div.backgroundimage //base64... } ]
client-side code
const MyArray=[],SaveBtn = document.queryselector("#save_div"); const SendArray = (ARRAY)=>{ socket.emit("div_data",ARRAY); } SaveBtn.onclick = ()=>{ SendArray(MyArray); }
server-side code
socket.on("div_data",(data)=>{ console.log(data) // function does not react. let JSON_DATA = JSON.stringify(data) console.log(JSON_DATA) // function does not react. });
Is this socket.io error? What should I do or how should I research this issue?
UPDATE
network tab in devtools
for two base64 image : (function work successfully)
for four base64 image : (function does not react)
-
Error when testing a React search component
Hi I´m getting this TypeError when testing my component, I don't know why the history is undefined
TypeError: Cannot read property 'push' of undefined 16 | e.preventDefault(); 17 | setSearchTerm(inputValue); > 18 | history.push(`/search/${inputValue}`);
here is my component:
const handleSubmit = (e) => { e.preventDefault(); setSearchTerm(inputValue); history.push(`/search/${inputValue}`);
and my test
it("Calls the handleSubmit function", () => { const handleSubmit = jest.fn(); fireEvent.submit(screen.getByRole("textbox")); expect(handleSubmit).toHaveBeenCalled();
-
how properly mock/test constructor with Jest
I'd like to test Module2 constructor as well as other its functions. What is the proper way to mock Module2 constructor without breaking testFunc1, testFunc2 to test with Jest.
// **************************************** // Module 1 component class Module1 { init() { // ........ } } module.exports = new Module1() // **************************************** // Module 2 component const module1 = require('./module1') class Module2 { constructor() { try { module1.init() } catch (err) { console.log('error') process.exit(1) } } testfunc1 = () => { // ........ } testfunc2 = () => { // ........ } } module.exports = new Module2()
-
How do I create a test for my services controller (Jest)?
I'm trying to create a test for my Animals List Services Controller, making sure the database query is tested. Right now with what I have, I have been able to mock the database query call to ensure the query is being called with the right parameters. However, i'm also trying to mock the return values from the database query call. I'm not sure how to mock dbResult in "services.ts" to get the rows property. Please I need some help, not sure how to do it. Thank you in advance.
I believe I was able to mock the database query call, however, is there a way to refactor or create a test to mock the return call of dbResult?
services.ts
import db from '../../modules/db'; import { DBGenericDataResponse } from '../../types/models'; export async function GetAnimalsList(): Promise<DBGenericDataResponse> { const lQuery = `select animalid, description from animal where active=1 order by sortorder, description`; const responseMessage: DBGenericDataResponse = { code: 200, status: 'ok', message: '', count: 0, data: [], error: '' }; try { const dbResult = await db.query<any>(lQuery); responseMessage.message = 'Animals Returned'; responseMessage.count = dbResult.rows.length; responseMessage.data = dbResult.rows; } catch (err) { responseMessage.code = 400; responseMessage.status = 'error'; responseMessage.message = 'Error retrieving Animals List'; responseMessage.error = err; } return responseMessage; }
ServicesTest.spec.ts
import * as Services from '../../../../src/controllers/animals/services'; import db from '../../../../src/modules/db'; describe('GetAnimalsList', () => { afterEach(() => { jest.resetAllMocks(); }); it('should call the database with the correct query parameter', async () => { const dbMock = jest.spyOn(db, 'query'); const response = await Services.GetAnimalsList(); expect(dbMock).toBeCalled(); expect(dbMock).toHaveBeenCalledWith( 'select animalid, description from animal where active=1 order by sortorder, description' ); }); });