我這里有一個回傳隨機十六進制顏色的函式
function randomHex() {
return `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
}
我怎樣才能用玩笑來測驗它?我想知道它是否真的回傳隨機十六進制
uj5u.com熱心網友回復:
參考我自己的話,來自這篇文章:
所以我們可以考慮如何測驗它,下面是拋硬幣的基本實作:
const flipCoin = () => Math.random() < 0.5 ? "heads" : "tails";我們可以確信,如果我們多次呼叫這個函式,我們將得到每個結果的大約一半:
> Array(10).fill(null).map(() => flipCoin()); [ "tails", "heads", "heads", "tails", "tails", "tails", "heads", "heads", "tails", "tails" ]但是對于給定的電話,我們無法確定它會是哪一個。那么我們如何為此撰寫測驗呢?我們可以再次使用外觀模式,提取
const random = () => Math.random()并用測驗替身替換它。這可以正常作業,但與實作緊密耦合:describe("flipCoin", () => { it("returns 'heads' when the random number is less than 0.5", () => { random.mockReturnValue = 0.3; expect(flipCoin()).toEqual("heads"); }); });一種替代方法是根據我們想要的實作的屬性撰寫測驗。例如,雖然我們不知道具體的值,但我們知道:
- 它應該總是給出預期的結果之一;和
- 它不應該總是給出相同的結果(否則
() => "heads"將是一個有效的實作)。
在這種情況下,基于屬性的測驗可能如下所示:
describe("randomHex", () => {
it("always returns a colour", () => {
const colours = Array(100).fill(null).map(() => randomHex());
colours.every((colour) => expect(colour).toMatch(/^#[\da-f]{6}$/));
});
it("doesn't always return the same colour", () => {
const colours = Array(100).fill(null).map(() => randomHex());
expect(new Set(colours).size).toBeGreaterThan(1);
// or a higher number, but e.g. `.toEqual(colours.length)` can fail due to collisions
});
});
uj5u.com熱心網友回復:
也許像
const { randomHex } = require('../../../');
describe('', () => {
it('', () => {
const firstRandomColor = randomHex();
const secondRandomColor = randomHex();
const hexRegex = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
expect(firstRandomColor).toMatch(hexRegex);
expect(secondRandomColor).toMatch(hexRegex);
expect(firstRandomColor).not.toBe(secondRandomColor);
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/481709.html
標籤:javascript 测试 开玩笑的
上一篇:測驗“記住”了嗎?獨立
