chai-almost

travis npm node

擴展 chai,提供允許數字「幾乎」相等(亦即,在彼此的容差範圍內)的斷言。這在處理浮點數捨入誤差或其他近似值時特別有用。

安裝

npm install chai-almost --save-dev

使用方式

若要使用,請匯入模組,然後使用 chai.use 來呼叫它

const chai = require('chai');
const chaiAlmost = require('chai-almost');

chai.use(chaiAlmost());

預設情況下,chai-almost 允許 1 x 10-6 的容差。這將讓大多數捨入誤差安全通過,但仍會拒絕大多數真正的非相等性。您可以透過在呼叫模組時將您想要的容差作為參數傳遞來覆寫此值

chai.use(chaiAlmost(0.1));

斷言

almost 斷言可以與深層或淺層相等性鏈式使用

// shallow
expect(3.9999999).to.almost.equal(4);	        // passes
expect(3.9).to.almost.equal(4);			// fails
expect(4.0000001).to.be.almost(4);		// passes
expect(4.1).to.not.be.almost(4);		// passes

// deep
expect({ taco: 'pastor', num: 3.9999999 }).to.almost.eql({ taco: 'pastor', num: 4 }); // passes
expect([[1, 2, 2.9999999], 1.0000001]).to.be.deep.almost([[1, 2, 3], 1]);             // passes
expect({ taco: 'pastor', num: 3.9 }).to.not.almost.eql({ taco: 'pastor', num: 4 });   // passes

對非數字的相等性檢查保持不變

expect('taco').to.almost.equal('taco');   // still passes
expect({ x: 5 }).to.be.almost({ x: 5 });  // still fails (shallow equality)
expect(['tacos', 2, 3]).to.be.deep.almost(['burritos', 2, 2.9999999]); // still fails

特定容差

一個用於淺層或深層相等性的單一實例自訂容差可以作為第二個參數傳遞給 almost

expect(10).to.be.almost(15, 10)                   // passes
expect([4, 2, 5]).to.be.deep.almost([3, 4, 7], 3) // passes