我正在使用 Jest 運行一些測驗。我已經定義了一些變數。一些測驗會修改變數,例如,將一個專案添加到陣列中。每次測驗后,我想將變數重置為最初分配給它們的值,因此每個測驗都有原始資料可供使用。這可能嗎?Jest 對此有解決方案嗎?
例如
import * as matchers from "jest-extended";
expect.extend(matchers);
const array = [1, 2, 3];
const addFour = array => array.push(4);
const addFive = array => array.push(5);
describe("tests", () => {
it("should add 4 to the array", () => {
addFour(array);
expect(array).toHaveLength(4);
});
//array should be [1, 2, 3, 4]
it("should add 5 to the array", () => {
addFive(array);
expect(array).toHaveLength(4);
});
//array should be [1, 2, 3, 5] and not [1, 2, 3, 4, 5]
});
我已經編輯了問題以更好地類似于我的測驗用例。問題已解決。請看下面。
uj5u.com熱心網友回復:
您可以使用 Jest 的beforeEach函式來初始化變數。
let array;
beforeEach(() => {
array = [1, 2, 3];
});
但是在您的示例中,addFour和addFive方法是不可變的,這意味著它們不會更改array變數的值。在這種情況下,不需要重置的值,array因為它永遠不會改變。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/536636.html
下一篇:直接從函式Python獲取變數
