我在 stack-overflow 上搜索过这个问题,但找不到任何与我的用例类似的东西。
我有这样的容器组件。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// API
import BookingAPI from '../../../../api/BookingAPI';
class CustomerProfilePage extends Component {
state = {
list: [],
totalRecords: 0,
pageNo: 1,
};
componentDidMount() {
const { pageNo } = this.state;
this.onGetBookingList({ pageNo });
}
onGetBookingList = async ({ pageNo = 0 }) => {
const { match } = this.props;
try {
const result = await BookingAPI.onGetBookingList({
passengerId: match.params.customerId,
sortProperties: ['id'],
limitCount: 10,
pageNo,
});
this.setState({ …Run Code Online (Sandbox Code Playgroud) 我正在尝试在我的组件中测试功能,基本思想是设置了一些状态,当按下按钮时,将调用具有设置状态的函数。代码有效,但是当我尝试测试它时,我没有得到预期的结果,就好像在测试期间从未设置过状态一样。
我在使用 Jest 和 Enzyme 测试的 React Native 应用程序中使用带有钩子 (useState) 的功能组件。
复制我的问题的一个例子是:
import React, { useState } from "react";
import { View, Button } from "react-native";
import { shallow } from "enzyme";
const Example = function({ button2Press }) {
const [name, setName] = useState("");
return (
<View>
<Button title="Button 1" onPress={() => setName("Hello")} />
<Button title="Button 2" onPress={() => button2Press(name)} />
</View>
);
};
describe("Example", () => {
it("updates the state", () => {
const button2Press = jest.fn();
const wrapper …Run Code Online (Sandbox Code Playgroud) 我有以下onSubmit功能代码
handleSubmit(event) {
event.preventDefault();
this.setState({ isDone: true });
const nameMatch= () => {
return !(this.state.firstName.match("^Cel.*") && this.state.firstName.endsWith("on"))
}
if (nameMatch()) {
alert("Please enter a valid name");
return;
}
if (!this.state.lastName.endsWith("on")) {
alert("check lastname too");
return;
}
this.getFullName();
}
Run Code Online (Sandbox Code Playgroud)
为了运行上面的测试,我这样做:
it('check submit', () => {
wrapper.handleSubmit({preventDefault: () => {}});
console.log(wrapper.handleSubmit());
});
Run Code Online (Sandbox Code Playgroud)
在此,我需要名字和姓氏的状态。我如何在测试用例中做到这一点?如何将它们作为参数传递给测试?
我想使用 Jest 和 Enzyme 编写一个测试,测试具有事件侦听器的组件,这样当给定 html 元素外部发生 mousedown 事件时,就会发生更改(在本例中,状态值被切换)。我正在使用 jest 来模拟事件侦听器并模拟 mousedown 事件,但是,当我尝试运行此测试时,我收到以下错误消息:
TypeError:无法在“Node”上执行“contains”:参数 1 不是“Node”类型。
显然,我认为<div />当我用 模拟 mousedown 事件时,这不是我应该提供的正确值map.mousedown({ target: <section /> });。如何正确模拟组件外部发生的 mousedown 事件?您可以看到下面的代码。谢谢!
示例组件.jsx:
import * as React from 'react';
const SampleComponent = () => {
const [state, setState] = React.useState(false);
const ref = React.useRef(null);
const handleClickOutside = (event) => {
if (
!ref.current.contains(event.target)
) {
setState(true);
}
};
React.useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
});
return ( …Run Code Online (Sandbox Code Playgroud) 我有一个使用“universal-cookie”的 React 组件。在测试用例中调用 mount 时,cookies 对象为空。
import Cookies from 'universal-cookie';
const cookies = new Cookies();
class MyComponent extends React.Component {
componentDidMount(){
axios.defaults.headers.common.Authorization = cookies.get('token').value; //12492525
}
}
//My Test File
describe('MyComponent Test', () => {
it('Component mounted', () => {
const wrapper = mount(<MyComponent/>);
});
});
Run Code Online (Sandbox Code Playgroud)
当我运行测试文件时,我不断收到错误
Cookie 附近的“类型错误:无法读取未定义的属性‘值’”。
无论我尝试模拟或设置多少次,Cookie 值都是空的。
到目前为止我尝试设置
cookies.set('HAS_DOCUMENT_COOKIE', true);
cookies.set('token', { value: '1244'});// in my test file
Run Code Online (Sandbox Code Playgroud) 我有 index.js 文件,其中包含:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App'
import * as serviceWorker from './serviceWorker';
import {combineReducers,createStore,compose,applyMiddleware} from 'redux'
import {Provider} from 'react-redux'
import thunk from 'redux-thunk'
import { HashRouter } from 'react-router-dom';
import playerReducer from './store/Player/PlayerReducers'
import cardReducer from './store/Cards/cardsReducer'
import playersReducer from './store/Players/PlayersReducer'
import stylesReducer from './store/Styles/StylesReducer'
import gameReducer from './store/Game/gameReducer'
const rootReducer = combineReducers({
player: playerReducer,
cards:cardReducer,
players:playersReducer,
styles:stylesReducer,
game:gameReducer
})
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store …Run Code Online (Sandbox Code Playgroud)我正在尝试用 Jest 和 Enzyme 在 React 上编写测试。但在调用.simulate('change')函数时,该值保持不变NULL,不会更改为预期值miqueias@gmail.com。我的应用程序.jsx:
const App = () => {
const [username, setUsername] = React.useState(null);
const [password, setPassword] = React.useState(null);
const handleChange = (event) => {
setUsername(event.target.value);
};
return (
<div
style={{
height: "100vh",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<input
type="email"
id="email"
value={username}
onChange={handleChange}
/>
<input
type="password"
id="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
<button>Enviar</button>
</div>
);
};
export default App;
Run Code Online (Sandbox Code Playgroud)
我的应用程序.test.js:
import React from 'react';
import …Run Code Online (Sandbox Code Playgroud) enzyme ×7
jestjs ×7
reactjs ×7
javascript ×2
react-hooks ×2
cookies ×1
mocking ×1
react-native ×1
unit-testing ×1