首页 > 解决方案 > 属性未定义时如何抛出测试?

问题描述

我希望这个测试抛出,因为它没有用户名。相反,它不会抛出并将用户名显示为未定义。

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();
});

我如何让它抛出?

标签: javascripttestingjestjs

解决方案


我想你应该稍微修一下你的课

class Post {

  constructor(user) {
    if (!user.name) throw 'invalid user name'

    this.username = user.name;
    this.description = user.description;
    this.photo = user.photo;
  }
}

推荐阅读