我正在尝试使用 Jest 和 Supertest 包来测试我的 API。我尝试使用import { request } from "supertest";
能够在我的文件中使用请求,但收到一个语法错误,指出模块 supertest 不提供名为“请求”的导出。
关于如何以这种方式使用它有什么想法吗?
我正在尝试将图像传递到我的节点服务器,但无论我尝试什么,当我将其作为 a 传递时,有效负载始终为空,像const formData = new FormData();
往常一样,我确实获得了正确的信息(除了没有新 FormData 就无法翻译的图像) ()),但其余部分通过有效负载发送。
这是我的 API:
/// POST SEND MESSAGE ///
export const postSendMessage = async (id, data) => {
const headers = {
'Content-Type': 'multipart/form-data',
'Accept-Language': currentLang,
}
const body = {
senderId: data.senderId,
text: data.text,
images: data.images,
}
try {
const response = await axios.post(`http://localhost:3001/patient/${id}/message`, body, { headers })
return response
}
catch (error) {
console.error('error', error);
}
return null
};
这是前端:
const ChatMessageInput = ({ conversationId }) => {
const userContext = useContext(AuthContext);
const fileRef = useRef(null);
const [message, setMessage] = useState('');
const [images, setImages] = useState([]);
const handleAttach = (event) => {
const newImage = event.target.files[0];
if (newImage && newImage.type.includes('image')) {
setImages(prevImages => [...prevImages, newImage]);
}
};
const handleChangeMessage = useCallback((event) => {
setMessage(event.target.value);
}, []);
const handleSendMessage = async (event) => {
if (event.key === 'Enter') {
try {
const formData = new FormData();
formData.append('text', message);
formData.append('images', images);
formData.append('senderId', userContext.user.id);
const messageSent = await API.postSendMessage(conversationId, formData);
setMessage('');
setImages([]);
} catch (error) {
console.error(error);
}
}
};
return (
<>
<InputBase
value={message}
onKeyUp={handleSendMessage}
onChange={handleChangeMessage}
placeholder="Type a message"
endAdornment={
<Stack direction="row">
<IconButton onClick={() => fileRef.current.click()}>
<Iconify icon="solar:gallery-add-bold" />
</IconButton>
</Stack>
}
/>
<input type="file" ref={fileRef} style={{ display: 'none' }} onChange={handleAttach} />
</>
);
}
据我了解,您无法 console.log formData,但是当我 console.logmessages
或images
我确实获得了正确的值时。我在这里缺少一些东西。
谢谢
所以,我有 4 次机会(机会 1、机会 2 等)。我想检查一个机会是否等于一,但其他机会都不等于一。我知道我可以检查每一个,但我最终会添加越来越多的机会,并且列表将非常长并且处理起来很烦人。
var chance1 = Math.floor(Math.random() * 10) + 1
var chance2 = Math.floor(Math.random() * 100) + 1
var chance3 = Math.floor(Math.random() * 1000) + 1
var chance4 = Math.floor(Math.random() * 10000) + 1
if (chance1 === 1) {
document.body.innerText = "Red - 1 in 10"
document.body.style.backgroundColor = "red"
}
if (chance2 === 1) {
document.body.innerText = "Orange - 1 in 100"
document.body.style.backgroundColor = "orange"
}
if (chance3 === 1) {
document.body.innerText = "Yellow - 1 in 1,000"
document.body.style.backgroundColor = "yellow"
}
if (chance4 === 1) {
document.body.innerText = "Green - 1 in 10,000"
document.body.style.backgroundColor = "green"
}
再次,我尝试检查每个值,它有效,但我认为最好有一种更有效的方法。
我想加载版本3.11.2的 nuxt 框架。我像下面的代码一样加载文件index.js
const express = require("express");
const { build, loadNuxt } = require("nuxt");
const { default: main, createHttpService } = require("@tinqjs/tinjs-boot");
const isDev = process.env.NODE_ENV !== "production";
const app = express();
// console.log(nuxt);
main(async () => {
const nuxt = await loadNuxt(isDev ? "dev" : "start");
// Use Nuxt's renderer
app.use(nuxt.render);
if (isDev) {
await build(nuxt);
}
const listen = createHttpService(app);
listen(3001, () => {
console.log(`Service frontend nuxtjs ready`);
});
});
我运行node index.js
但出现错误
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /node_modules/nuxt/package.json
如何解决这个错误?请帮我...
问题
我发现当 JSDoc 类型的代码位于项目“内部”时,JSDoc 可以很好地与智能感知和类型检查配合使用;但是,通过脚本标记 ( ) 包含 JSDoc 类型库<script src="mylibrary.js">
不会提供任何智能感知、类型检查或提示。
我的目的是发布一个包含类型的库,我希望 JSDoc 允许我这样做,即使对于那些想要通过标签包含脚本而不是使用 NPM 安装和导入的用户来说,一个.d.ts
文件就足够了。
我很感激任何人都能提供的任何见解。
假设
我的猜测是,TypeScript 检查器无法访问脚本标记中包含的代码,即使该脚本是本地的,但由于我没有看到任何直接说明这一点的内容,所以我想在这里检查我的理解。我是 TypeScript 用户,但对 JSDoc 很陌生,所以我可能会错过一些细微差别。
细节
我将 VSCode 与 Microsoft 的“JavaScript 和 TypeScript Nightly”插件一起使用。
我的库代码的工作原理如下:
/**
* @preserve
* @typedef {object} LibObj - The main library object
* @property {string} LibObj.name - The name of the library
*/
globalThis.LibObj = {
name: "My Library's Name"
}
当我将库代码包含到 HTML 页面中LibObj
并LibObj.name
具有any
类型时,我没有得到智能感知。
import React, { useState, useEffect } from 'react';
function Child() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const interval = setInterval(() => {
setTime(new Date());
}, 1000);
}, []);
return <p>The current time is: {time.toLocaleTimeString()}</p>;
}
export default Child;
我无法理解时间每秒如何变化,因为我们知道我已将依赖项作为空数组给出,它应该只更新一次,但每秒更新一次,但你如何解释,所以任何人都可以解释代码是如何工作的
只要其他 if 语句不存在,以下每个 if 语句都可以完美运行。
我不明白为什么同时使用两个 if 语句会导致该函数无法工作。
我尝试了很多变体,但无法弄清楚。
这是代码:
$("a").click(function(event){
event.preventDefault();
let lItem = document.querySelectorAll(".listing-item");
let mItem = document.querySelectorAll(".menu-item");
let destination = $(this).attr("href");
if ( $(this).parent(lItem) ) {
tlUp.tweenTo(0, {
onComplete: () => {
window.location = destination;
}
});
}
if ( $(this).parent(mItem) ) {
tlMenu.tweenTo(0, {
onComplete: () => {
window.location = destination;
}
});
}
});
我的自定义复选框组件出现问题。
我的目标是让父母能够控制输入的选定状态。但每次我单击该复选框时,即使父级中未设置任何内容,它也会被选中。我怀疑它与 Svelte 没有直接关系,更像是与复选框行为相关。
<script lang="ts">
import { createEventDispatcher } from "svelte";
export let checked = false;
const dispatch = createEventDispatcher();
function handleClick(event) {
// Emit a custom event to notify the parent that the checkbox was clicked
dispatch('click', { checked: !checked });
}
</script>
<input type="checkbox" checked={checked} on:click={handleClick} />
<style>
input[type='checkbox']:not(:disabled):is(:checked) {
height: 35px;
width: 35px;
}
</style>
我在这里缺少什么?
我尝试了自定义事件、双向绑定,但没有任何帮助。如果想测试的话,这里有一个stackblitz 链接。
谢谢
所以我做了一个简单的游戏,点击一个按钮,计时器设置为 5 秒,每次点击计数器都会增加(一切都在同一个文件 [index.html] 中运行)。每当我尝试将代码放入独立文件中,例如 js.js 和 index.html 时,锚点为:
<script src="js.js"></script>
它只是不起作用,并且显示错误,例如: Uncaught TypeError TypeError: Cannot readproperties of null (reading 'addEventListener')
这是 JS 和 HTML 代码:
// Global variables
const clickButton = document.getElementById('clickButton');
const counterElement = document.getElementById('counter');
// Counter
let counter = 0;
clickButton.addEventListener('click', () => {
counter++;
counterElement.textContent = counter;
moveButtonRandomly();
});
// Timer
let timeLeft = 5;
let timerElement = document.getElementById('timer');
let timer;
function countdown() {
if (timeLeft > 0) {
timeLeft--;
timerElement.textContent = timeLeft;
} else {
clearInterval(timer);
alert('Game Over! You lose!');
}
};
function startTimer() {
timer = setInterval(countdown, 1000);
}
function resetTimer() {
clearInterval(timer);
timeLeft = 5;
timerElement.textContent = timeLeft;
}
document.getElementById('startofthegame').addEventListener('click', startTimer);
document.getElementById('clickButton').addEventListener('click', startTimer);
// Random button position
function moveButtonRandomly() {
const randomX = Math.random() * (window.innerWidth - clickButton.offsetWidth);
const randomY = Math.random() * (window.innerHeight - clickButton.offsetHeight);
clickButton.style.left = randomX + 'px';
clickButton.style.top = randomY + 'px';
}
// Start of the actual game after clicking "START!" button
document.getElementById("startofthegame").addEventListener("click", moveButtonRandomly);
const start = document.getElementById("startofthegame");
start.addEventListener("click", hidden)
function hidden() {
var button = document.querySelector(".hidden");
button.classList.remove("hidden")
var button2 = document.querySelector(".text")
button2.setAttribute("style", "display: none;")
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="js.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Position Button</title>
</head>
<body>
<div class="text">
<p>Welcome to simple clicking game!</p>
<button id="startofthegame" class="start">Start!</button>
</div>
<div class="hidden">
<button id="clickButton" onclick="resetTimer()">Click me</button>
<p>Counter: <span id="counter">0</span></p>
<p>Time left: <span id="timer">5</span> seconds</p>
</div>
</script>
</body>
</html>
我尝试使用 DOMContentLoading 加载页面,但仍然不起作用,尝试重做一些代码行,但仍然失败,整个页面都损坏了。我真的不知道如何解决这个问题。
(抱歉,如果我的代码是意大利面条式的,你们中的一些人可以用少 50% 的行数完成它,但我是一个初学者,想自己尝试一些东西)
我目前遇到一个情况,我想为我的自定义钩子编写一个单元测试,useMyHook
其中称为useLocation
钩子的一个简单例子是……。像这样:
import { useState, useEffect } from 'react'
import { useLocation } from 'react-router-dom'
const useMyHook = () => {
const { pathname } = useLocation()
const { myState, setMyState } = useState()
useEffect(() => {
switch(pathname) {
case '/':
setMyState('a')
break
case '/b':
setMyState('b')
break
default:
setMyState('c')
break
}
}, [pathname])
return myState
}
我的测试是这样的:
import { renderHook } from '@testing-library/react-hooks'
import useMyHook from '../useMyHook'
describe('useEventId', () => {
it('path matches roleSelection', () => {
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'), // since you still want to use the actual MemoryRouter
useLocation: () => ({
pathname: '/',
}),
}))
const state = renderHook(() => useMyHook())
expect(state).toBe('a')
})
})
但是,我不断收到此错误:
useLocation() 只能在组件的上下文中使用。
谁能指出测试这种自定义挂钩的正确方法是什么?