Chai等断言库如何在不强制调用函数的情况下工作?

knp*_*wrs 11 javascript assert function assertions chai

Chai,您可以执行以下操作:

expect({}).to.exist;
Run Code Online (Sandbox Code Playgroud)

exist不是函数调用,但这仍然适用于测试框架.反向(expect({}).to.not.exist)导致测试失败,但同样,exist不是函数调用.

这些断言如何在不让我调用函数的情况下工作?事实上,如果我试图说expect({}).to.exist()测试失败,因为exist它不是一个函数.

knp*_*wrs 11

我想通了(至少,我想出了一个方法).使用JavaScript getter:

var throws = {
  get a() {
    throw new Error('a');
  },
  get b() {
    throw new Error('b');
  },
  get c() {
    throw new Error('c');
  }
};
Run Code Online (Sandbox Code Playgroud)

在执行throws.athrows.b,或者throws.c,将抛出相应的错误.

从那时起,构建Chai中包含的断言相当容易.