哪里可以使用Jasmine Matchers进行JavaScript测试
我曾尝试使用Jasmine Matchers,它确实为我提供了有关错误消息的详细信息。单元测试也变得有意义,但当涉及到分布式和大规模项目时,我不确定匹配器如何发挥好作用 下面是一个示例脚本的matcher示例哪里可以使用Jasmine Matchers进行JavaScript测试,javascript,jasmine,karma-jasmine,Javascript,Jasmine,Karma Jasmine,我曾尝试使用Jasmine Matchers,它确实为我提供了有关错误消息的详细信息。单元测试也变得有意义,但当涉及到分布式和大规模项目时,我不确定匹配器如何发挥好作用 下面是一个示例脚本的matcher示例 beforeEach(function () { jasmine.addMatchers({ toBeAGoodInvestment: toBeAGoodInvestment }); }); function toBeAGoodInvestment() {
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 matchers单元测试用例和自定义matcher。我不确定这对一个更大的项目有什么帮助。如果在如何使用这些匹配器背后有任何原则指导,那就太好了我不认为项目的规模与编写定制Jasmine匹配器的有用性之间存在直接而明确的关联 引入定制Jasmine matchers可以对测试代码的质量、可读性和紧凑性产生多方面的积极影响,而不管代码库的大小:
- 为公共断言检查创建自定义匹配器有助于不违反
- 它也是一种重构方法
另一个经常被忽略的点是,定制匹配器应该引入任何副作用或更改断言下的对象。这可能会导致难以调试的意外情况。我认为项目的规模与编写定制Jasmine matchers的实用性之间没有直接而明确的关联 引入定制Jasmine matchers可以对测试代码的质量、可读性和紧凑性产生多方面的积极影响,而不管代码库的大小:
- 为公共断言检查创建自定义匹配器有助于不违反
- 它也是一种重构方法
另一个经常被忽略的点是,定制匹配器应该引入任何副作用或更改断言下的对象。这可能会导致难以调试的意外情况