javascript - 属性未定义时如何抛出测试?
问题描述
我希望这个测试抛出,因为它没有用户名。相反,它不会抛出并将用户名显示为未定义。
Post.js
class Post {
constructor({username, description, photo}) {
this.username = username;
this.description = description;
this.photo = photo;
}
}
Post.Test.js
test('post must have a username', () => {
expect(() => new Post({description: 'a', photo: 'photo.jpg'})).toThrow();
});
我如何让它抛出?
解决方案
我想你应该稍微修一下你的课
class Post {
constructor(user) {
if (!user.name) throw 'invalid user name'
this.username = user.name;
this.description = user.description;
this.photo = user.photo;
}
}
推荐阅读
- ios - flutter:连接Linux开发机和远程Xcode进行构建和iOS模拟器
- php - 有没有更好的方法在使用 PHP 的 Bootstrap CSS 中每隔 3 行打破列?等宽多行
- c++ - std::normal_distribution 的性能问题?
- c# - Assembly.LoadFrom 有效,Assembly.Load 无效
- jenkins - Jenkins - 错误消息 431 原因:请求标头字段太大
- c# - 在 Xamarin.Android 使用的 NuGet 包中包含本机库
- javascript - [Vue 警告]:使用带有参数的 mixin 时无法挂载组件
- android - 将触摸事件从对话框片段传递到正下方的视图(在父活动内)
- google-apps-script - 在 Google 表格上的脚本中从右到左对齐希伯来语文本
- php - 执行数据库连接的 PHP 脚本后未显示成功或失败消息