gpt4 book ai didi

javascript - 用 enzyme 测试支柱钻井

转载 作者:行者123 更新时间:2023-12-01 00:57:00 25 4
gpt4 key购买 nike

我想编写一个集成测试来断言,当父组件将某些值或属性钻取到子组件时,该组件会接收所述值并正确呈现它们。下面我有两个组件示例和一个示例测试。当然,测试并不准确,但我想知道如何使用 enzyme 来实现这一点?谢谢!

sampleComponent.js:

import React from 'react';

const SampleComponent = () => (
<div test-attr="div">
<SampleChildComponent title="Sample title" />
</div>
);

export default SampleComponent;

sampleChildComponent.js:

import React from 'react';

const SampleChildComponent = ({ title }) => <h3 test-attr="h">{title}</h3>;

export default SampleChildComponent;

sampleComponent.test.js:

import React from 'react';
import { shallow } from 'enzyme';
import SampleComponent from './sampleComponent';
import SampleChildComponent from './sampleChildComponent';

test('renders component without errors', () => {
const wrapper = shallow(<SampleComponent />);
const childWrapper = shallow(<SampleChildComponent />);
expect(childWrapper.text()).toEqual('sample title');
});

最佳答案

要渲染子组件,您应该使用 mount 而不是 shallow:

import { mount } from 'enzyme'
import React from 'react'
import SampleChildComponent from './sampleChildComponent'
import SampleComponent from './sampleComponent'

test('renders component without errors', () => {
const wrapper = mount(<SampleComponent />)
expect(wrapper.find(SampleChildComponent).text()).toEqual('sample title')
})

关于javascript - 用 enzyme 测试支柱钻井,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56485449/

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