gpt4 book ai didi

javascript - 动态创建的嵌套描述和行为 "it"s

转载 作者:行者123 更新时间:2023-11-30 19:40:54 25 4
gpt4 key购买 nike

我在我的测试中嵌套了 describe 并且像往常一样我使用了一些 beforeEach 和 before in describes。我的 describe 函数之一调用了创建动态测试 (DRY) 的辅助函数。 mocha 运行 description 嵌套 describe before beforeEach 方法。我动态创建的 it 的 comp 为 undefined

const checkProps = (comp, propName, expectedvalue) => {
it(`${comp} should have ${propName} equal to ${expectedvalue}`, () => {
expect(comp.prop(propName)).to.equal(expectedvalue);
});
};

describe('Component', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<MyComponent />);
});

describe('prop checking', () => {
checkProps(wrapper, 'title', 'SomeTitle');
});
});

最好的方法是什么?提前致谢。

最佳答案

会发生什么

Mocha Run Cycle首先运行所有 describe 回调函数(...对于其他测试框架也是如此,例如 JestJasmine)。

然后它运行 before Hook ,然后运行 ​​beforeEach Hook ,最后运行 it 回调。

所以 checkProps 作为运行初始 describe 回调的一部分运行,此时 wrapperundefined ,因此您已经注意到测试说明说 undefined should have...

beforeEach 钩子(Hook)在 it 回调函数运行之前运行...但是它重新定义 wrapper 所以当it 回调运行 comp 仍然是 undefined 并且测试失败:

  1) Component
prop checking
undefined should have title equal to SomeTitle:
TypeError: Cannot read property 'prop' of undefined
at Context.prop (test/code.test.js:15:19)

解决方案

有几件事需要改变:

  • 组件名称需要在 it 运行时可用,而此时 wrapper 尚不存在,因此您必须自己传递名称。<
  • 如果您将一个对象传递给 checkProps,那么您可以在 beforeEach 期间为该对象设置一个 wrapper 属性并访问该 wrapper 属性在您的测试中,因为该对象永远不会被重新定义。

这是一个工作测试,可以让您更接近您正在尝试做的事情:

import * as React from 'react';
import { shallow } from 'enzyme';

const MyComponent = () => (<div title="SomeTitle">some text</div>);

const checkProps = (name, obj, propName, expectedvalue) => {
it(`${name} should have ${propName} equal to ${expectedvalue}`, () => {
expect(obj.wrapper.prop(propName)).to.equal(expectedvalue); // Success!
});
};

describe('Component', () => {
const obj = {};
beforeEach(() => {
obj.wrapper = shallow(<MyComponent />);
});

describe('prop checking', () => {
checkProps('MyComponent', obj, 'title', 'SomeTitle');
});
});

关于javascript - 动态创建的嵌套描述和行为 "it"s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55415555/

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