gpt4 book ai didi

javascript - 使用不同的 beforeEach 多次运行测试

转载 作者:行者123 更新时间:2023-12-02 23:59:52 26 4
gpt4 key购买 nike

所以我的测试中有这两种情况。第一个工作正常,在第二个中,我尝试在外部提取 beforeEach 声明,但它失败了,但我不明白为什么。这是一个简单的情况,基本上我尝试定义一个数组并对其进行循环,以便使用不同的 beforeEach 参数声明多次运行测试。

案例1

var params;

describe('When initializing', function () {
beforeEach(function () {
params = {
name: 'test 1'
};
});

it('should ..', function () {
params.name = 'test 2';
expect(...); => success
});

it('should ..', function () {
expect(...); => success because it expects params.name to be 'test 1' and it is 'test 1'
});
});

案例2

var params;

var test = {
name: 'test 1'
};

describe('When initializing', function () {
beforeEach(function () {
params = test;
});

it('should ..', function () {
params.name = 'test 2';
expect(...); => success
});

it('should ..', function () {
expect(...); => fails because it expects params.name to be 'test 1' and it is 'test 2'
});
});

在第二个测试中,如果我在描述中 console.log(test.name) ,我将得到 test 2,不知怎的,它被覆盖了,即使之前的 it 只是做了 params.name = 'test 2'; 而不是 test.name = 'test 2';

最佳答案

区别在于,在情况 1 中,每次调用 beforeEach 时都会创建一个新对象,而在情况 2 中则不然。

与此相结合的是,您的第一个测试会改变对象。如果所有测试都引用同一对象(即情况 2),则该突变将影响第一个测试后运行的任何代码。相反,如果在每次测试之前都覆盖该对象(情况 1),则该突变不会影响其他测试。

有几种方法可以解决这个问题。一是只保留case 1;通过每次重置为已知状态,您可以为所有测试提供一个干净的状态。另一种选择是不改变对象。也许测试可以复制该对象,然后修改该副本。

关于javascript - 使用不同的 beforeEach 多次运行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55223579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com