这个问题真的很好:Jest Mock module per test
它只是没有回答我的问题,即如何仅在一个测试中模拟它并使用原始组件保留其余部分。
如果我想对快照进行一些模拟而不是对其他测试进行一些模拟,那就有意义了
这是我目前的尝试
import React from 'react'
import { render } from '@testing-library/react'
jest.mock('components/Photo', () =>
jest.fn(() => jest.requireActual('components/Photo'))
)
import Photo from 'components/Photo'
import PhotoGrid from '.'
beforeEach(() => {
Photo.mockReset()
})
test('default renders 9 photos if provided 9', () => {
const photos = [...Array(9).keys()]
const { getAllByTestId, debug } = render(<PhotoGrid photos={photos} />)
debug()
expect(getAllByTestId(PHOTO_COMP_TEST_ID)).toHaveLength(9)
})
test('renders with masonry grid style', () => {
Photo.mockImplementation(() => <div />)
const photos = …Run Code Online (Sandbox Code Playgroud) javascript unit-testing reactjs jestjs react-testing-library
我正在尝试了解 React 和 Redux 测试的过程,我正在使用测试库来使用dom 节点查询来测试我的项目,但我仍然对在 React 项目中测试 Redux 实现的方式感到困惑:
我创建了一个自定义渲染函数,而不是反应测试库中的普通渲染方法
import React from 'react'
import { render as rtlRender } from '@testing-library/react'
import { Provider } from 'react-redux'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares);
//test-utils.js
//creating a custom render function so we can wrap our App with
//react-redux provider
const render = (ui, initialState) => {
const store = mockStore(initialState);
//App wrapper and mocked store passed to …Run Code Online (Sandbox Code Playgroud) 在我的登录表单中,成功登录会启动一个承诺链,最终用户被重定向到主屏幕。在下面的测试中,我希望通过捕获最后一步来确保我的登录有效。
我在代码中包含日志语句,告诉我承诺链中的每个步骤都按我的预期执行,但断言仍然失败。从我的日志记录可以清楚地看出,测试在承诺链执行之前完成。
我认为这可能会因为我在实际形式中使用的 Formik 的行为而变得复杂。我无法成功查询并等待登录时显示的微调器。
我不知道如何让这个测试等到导航发生。可以触发什么承诺决议waitFor来完成?
import { act, render, screen, waitFor } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import React from "react"
import { AuthProvider } from "context/auth-context"
import { rest } from "msw"
import { setupServer } from "msw/node"
import { MemoryRouter as Router } from "react-router-dom"
import { LoginScreen } from "screens/login"
import { handlers } from "test/auth-handlers"
import { buildLoginForm } from "test/generate/auth"
import { deferred } from "test/test-utils"
const Wrapper = ({ children …Run Code Online (Sandbox Code Playgroud) 我正在构建一个使用 React-query 来获取数据的 NextJS 应用程序。
我现在正在尝试实现一个测试框架。但是,当我运行时yarn test,出现以下错误。从react-query文档中,我了解到错误通常与<QueryClientProvider>未包含在_app.js.
我怀疑我需要为反应查询引入一些“模拟数据”,index.test.js但无法找到有关如何执行此操作的文档。
No QueryClient set, use QueryClientProvider to set one
Run Code Online (Sandbox Code Playgroud)
/测试/index.test.js
No QueryClient set, use QueryClientProvider to set one
Run Code Online (Sandbox Code Playgroud)
/pages/index.js
import { render, screen } from '@testing-library/react';
import Home from '../pages/index';
describe('Home', () => {
it('renders without crashing', () => {
render(<Home />);
expect(
screen.getByRole('heading', { name: 'Welcome to Next.js!' })
).toBeInTheDocument();
});
});
Run Code Online (Sandbox Code Playgroud)
/pages/_app.js
import Link from 'next/link';
import { …Run Code Online (Sandbox Code Playgroud) 在我的测试中,组件接收其 props 并设置组件。
这会触发 useEffect 发出 http 请求(我模拟)。
返回获取的模拟 resp 数据,但 useEffect 内的清理函数已被调用(因此组件已卸载),因此我收到所有这些错误。
如何防止组件卸载以便更新状态?我尝试过采取行动,没有采取行动,没有任何原因导致组件等待获取完成。
我应该说我的警告只是警告,但我不喜欢所有的红色,它表明出了问题。
export const BalanceModule = (props) => {
const [report, setReport] = useState();
useEffect(() => {
fetch('http://.....').then((resp) => {
console.log("data returned!!!")
setReports((report) => {
return {...report, data: resp}
})
})
return () => {
console.log("unmounted!!!")
};
}, [report])
.... trigger update on report here
}
// the test:
test("simplified-version", async () => {
act(() => {
render(
<BalanceModule {...reportConfig}></BalanceModule>
);
});
await screen.findByText("2021-01-20T01:04:38");
expect(screen.getByText("2021-01-20T01:04:38")).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud) 所以我试图测试 onSubmit 函数是否在单击按钮时被触发 - 我这样做的方式是通过测试 onSubmit 函数的内部正在获取调用(axios post 方法)
考试
describe('RecipeSearch', () => {
test('submit button should return post function to recipes/search/', () => {
let mock = new MockAdapter(axios);
userEvent.selectOptions(screen.getByRole('combobox'), 'Sweet');
userEvent.click(screen.getByText('Search'));
const config = {
headers: {
'Content-Type': 'application/json',
},
};
const searchRecipes = mock.onPost(
`${process.env.REACT_APP_API_URL}/recipes/search/`,
{ flavor_type: 'Sweet' },
{ config }
);
expect(searchRecipes).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
错误
expect(received).toHaveBeenCalled()
Matcher error: received value must be a mock or spy function
Received has type: object
Received has value: {"abortRequest": …Run Code Online (Sandbox Code Playgroud) 我的 React 项目有一些代码用于监听消息事件。
const onMessage = ({ data }) => {
console.log('On onMessage has been fired');
}
window.addEventListener('message', onMessage);
Run Code Online (Sandbox Code Playgroud)
有谁知道如何从我的测试套件中触发此事件?我尝试过诸如事件之类的库和许多诸如
test('Recieves message', async () => {
//Some setup..
//trigger the addEventListener('message')
window.parent.postMessage('Hello', '*'); //doesn't work
window.postMessage('Hello', '*'); //doesn't work
const ee = new events.EventEmitter();
ee.emit('Hello') //doesn't work
//Some further tests...
})
Run Code Online (Sandbox Code Playgroud)
似乎什么都不起作用。请注意,我需要小心这个测试,我不会模拟并覆盖所有addEventListener. 我仍然需要核心代码来完成我想要做的事情。我只需要从我的测试中触发或发出消息事件
我有一个表格,在处理时显示“正在提交”状态,在完成后显示“已提交”状态。
这是我正在使用的提交处理程序......
const handleSubmit = (e, _setTitle) => {
e.preventDefault()
_setTitle('Submitting...')
try {
doformStuff(emailRef.current.value)
} catch (err) {
throw new Error(err)
} finally {
_setTitle('Submitted perfectly.')
}
}
Run Code Online (Sandbox Code Playgroud)
我想测试提交状态是否出现,无论多短。
it('shows "submitting" when submitting', async () => {
// arrange
render(<MobileEmailCapture/>)
// act
const emailInput = screen.getByPlaceholderText('yourem@il.com')
userEvent.type(emailInput, fakeEmail)
fireEvent.submit(screen.getByTestId('form'))
// assert
expect(screen.getByTestId('title')).toHaveTextContent('Submitting...')
})
Run Code Online (Sandbox Code Playgroud)
问题是测试直接跳转到提交状态
Error: FAILED Expected 'Submitted perfectly.' to match 'Submitting...'.
我知道这就是最终的结果,但我想测试临时过渡状态。我怎么做?
我尝试测试我的悬停是否有效,这是我要测试的代码
//styled components + typescript
const Info = styled.div`
opacity: 0;
width:100%;
height: 100%;
position: absolute;
top:0;
left:0;
background-color: rgba(0,0,0,0.2);
z-index:3;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.5s ease;
cursor: pointer;
`
const Container = styled.div`
flex:1;
margin:5px;
min-width:280px;
height:350px;
display: flex;
align-items: center;
justify-content: center;
background-color: #f5fbfd;
position: relative;
&:hover ${Info}{
opacity: 1;
}
`
const ProductItem = ({item}:ProductItemProp) => {
return (
<Container data-testid="productContainer">
<Circle/>
<Image src={item.img}/>
<Info data-testid="productInfo">
<Icon data-testid="productIcon">
<ShoppingCartOutlined/>
</Icon>
<Icon>
<SearchOutlined/>
</Icon> …Run Code Online (Sandbox Code Playgroud) 我在为 Snowpack 项目设置 Jest 和 React 测试库时遇到问题,想知道你们中是否有人遇到过类似的情况。所以我收到的错误是The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'指向 。const { SNOWPACK_PUBLIC_BASE_URL } = import.meta.env;我已按照所有文档正确设置配置,但仍然收到此错误。我的配置文件如下。
package.json:
{
"jest": {
"verbose": true,
"preset": "ts-jest",
"testEnvironment": "node",
"transform": {
"node_modules/variables/.+\\.(j|t)sx?$": "ts-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!variables/.*)"
],
"moduleNameMapper": {
"@app/(.*)": "<rootDir>/src/$1",
"@auth/(.*)": "<rootDir>/src/auth/$1",
"@hooks/(.*)": "<rootDir>/src/hooks/$1",
"@gtm/(.*)": "<rootDir>/src/gtm/$1"
}
},
"scripts": {
"start": "snowpack dev",
"build": "snowpack build",
"test": "jest __tests__/ --coverage",
"test:watch": "jest --watch",
"format": "prettier --write …Run Code Online (Sandbox Code Playgroud) reactjs ×9
jestjs ×6
testing ×2
unit-testing ×2
dom ×1
forms ×1
javascript ×1
next.js ×1
postmessage ×1
react-query ×1
redux ×1
snowpack ×1
typescript ×1
use-effect ×1