我们可以在哪里使用Jasmine匹配器进行JavaScript测试

Where can we use Jasmine Matchers for JavaScript Testing

本文关键字:测试 JavaScript Jasmine 在哪里 我们      更新时间:2023-09-26

我尝试过使用Jasmine匹配器,它确实给了我关于错误消息的非常深入的细节。单元测试也变得有意义,但当涉及到分布式和大规模项目时,我不确定匹配器如何发挥良好的作用。

下面是我的匹配器示例脚本。

beforeEach(function () {
    jasmine.addMatchers({
        toBeAGoodInvestment: toBeAGoodInvestment
    });
});
function toBeAGoodInvestment() {
    return {
        compare: function (actual, expected) {
            // Matcher Definition
            var result = {};
            result.pass = actual.isGood();
            if (actual.isGood()) {
                result.message = 'Expected investment to be a bad investment';
            } else {
                result.message = 'Expected investment to be a good investment';
            }
            return result;
        }
    }
}

和规范文件如下

describe('Investment', function () {
   var stock, investment;
   beforeEach(function () {
      stock = new Stock();
      investment = new Investment({
         stock: stock,
         shares: 100,
         sharePrice: 20
      });
   });
   it('should be of a stock', function () {
      expect(investment.stock).toBe(stock);
   });
   it('should have invested shares quantity', function () {
      expect(investment.shares).toBe(100)
   });
   it('should have the share paid price', function () {
      expect(investment.sharePrice).toBe(20);
   });
   it('should have a cost', function () {
      expect(investment.cost).toBe(2000)
   });
   describe('when its stock share price valorizes', function () {
      beforeEach(function () {
         stock.sharePrice = 40;
      });
      it('should have a positive roi', function () {
         expect(investment.roi()).toEqual(1);
      });
      it('should be a good investment', function () {
         expect(investment.isGood()).toEqual(true);
      });
      it('matcher: should be a good investment', function () {
         expect(investment).toBeAGoodInvestment();
      });
   });
});

我已经添加了默认的Jasmine匹配器单元测试用例以及自定义匹配器。我不确定这在一个更大的项目中有什么帮助。如果有任何关于如何使用这些匹配器的原则指导,那就太好了

我不认为在项目的大小和编写自定义Jasmine匹配器的有用性之间存在直接和明确的关联。

引入自定义Jasmine匹配器可以对测试代码的质量、可读性和紧凑性产生多重积极影响,而不管代码库的大小:

  • 为通用断言检查定制匹配器有助于避免违反DRY原则
  • 它也是一个"提取方法"重构方法

尽管作者有责任使匹配器在断言错误发生时提供清晰易懂的反馈。我不确定在你的情况下,"好"answers"坏"的投资规则有多清楚,但是,乍一看,我想说的错误是:

预期投资是好的投资

不够清晰-将其与a比较,例如:

预期投资是好的投资。共享价格低于配置的最小值(30)。

换句话说,当它失败时,给出尽可能多的信息,告诉所有的事情。


另一个经常被忽视的点是自定义匹配器应该引入任何副作用或改变断言下的对象。这可能会导致难以调试的意外。