javascript - 检查状态更新的测试用例似乎没有给出正确的输出
问题描述
我有一个简单的函数,可以在单击事件上将组件的状态从 true 切换为 false。 这是功能
public toggleAvailability(dayTime: string): void {
const isAvailable = this.state[dayTime] === false ? true : false;
this.setState(
{ [dayTime]: isAvailable },
() => {
const instructor = {
userId: this.props.userId,
availability: this.state.friEarlyAfternoon
};
this.props.updateInstructor(instructor);
});
}
我正在使用 Jest+Enzyme 进行单元测试,并且我正在尝试按如下方式测试我的切换功能:
describe('Method toggleAvailability()', () => {
function test_toggleAvailability(dayTime: string, currentState: boolean, toggledState: boolean): void {
beforeEach(() => {
wrapper.setState({
dayTime: currentState,
});
wrapper.instance().toggleAvailability(dayTime);
});
it(`Sets the state's ${dayTime} to ${toggledState}`, () => {
expect(wrapper.state().dayTime).toEqual(toggledState);
});
}
test_toggleAvailability('monEarlyMorning', false, true);
test_toggleAvailability('monEMorning', true, false);
});
有人在这里有建议吗?
解决方案
任何时候根据现有状态设置状态,都必须使用回调版本setState
和它传递给您的状态参数,因为状态更新是异步的,并且可以一起批处理。
所以这:
const isAvailable = this.state[dayTime] === false ? true : false;
this.setState(
{ [dayTime]: isAvailable },
() => {
const instructor = {
userId: this.props.userId,
availability: this.state.friEarlyAfternoon
};
this.props.updateInstructor(instructor);
});
应该是这样的,你也为第一个参数传入一个函数:
this.setState(
prevState => {
const isAvailable = prevState[dayTime] === false ? true : false;
return { [dayTime]: isAvailable };
},
() => {
const instructor = {
userId: this.props.userId,
availability: this.state.friEarlyAfternoon
};
this.props.updateInstructor(instructor);
}
);
旁注:或者,如果您实际上不需要严格相等=== false
,则可以使用!
:
this.setState(
prevState => ( { [dayTime]: !prevState[dayTime] } ),
() => {
const instructor = {
userId: this.props.userId,
availability: this.state.friEarlyAfternoon
};
this.props.updateInstructor(instructor);
}
);
推荐阅读
- api - Blazor WebAssembly 和 HTTP 请求。如何防止计划外请求?
- node.js - 如何使用 innerJoinAndSelect 服务加入 typeORM 中的表
- html - 删除导航栏和图像之间的空间
- python - 从 python 生成器中抽取随机样本
- python - 为什么 go.Scatter 打印额外的行而 px.line 不是?
- typo3 - 使用 RouteEnhancers 将两个 GET 参数映射到说话 URL 将无法正常工作
- angular - 如何通过 Typescript 发布 GMT 日期?
- javascript - 函数未返回,但 console.log 显示内容
- sql - 存储过程 SQL 中的比较运算符
- flutter - Flutter beta SDK >= 1.22.0 - IDE 问题