gpt4 book ai didi

reactjs - 功能组件中的 Jest/ enzyme 模拟功能

转载 作者:行者123 更新时间:2023-12-03 13:27:43 25 4
gpt4 key购买 nike

我有一个功能组件,我想用模拟功能测试它(简化演示)

const remove = () => {
... do something
}

const removeButton = (props) => (
<Button onClick={() => remove()}>
Remove
</Button>
);

我尝试过这个测试用例

it('test remove button', () => {
const test = shallow(<removeButton/>)
const mockFunction = jest.fn()
test.instance().remove = mockFunction
test.find('Button').simulate('click')
expect(mockFunction).toHaveBeenCalled()
})

.instance().remove 无法模拟该函数,因为它超出了范围。我如何模拟删除函数?

最佳答案

这是一个工作示例:

// ---- comp.js ----
import * as React from 'react';
import * as comp from './comp';

export const remove = () => {
// ...do something
}

export const RemoveButton = (props) => (
<div onClick={() => comp.remove()}>
Remove
</div>
);


// ---- comp.test.js ----
import * as React from 'react';
import { shallow } from 'enzyme';

import * as comp from './comp';

describe('removeButton', () => {
it('should call remove on click', () => {
const mock = jest.spyOn(comp, 'remove');
mock.mockImplementation(() => {});
const component = shallow(<comp.RemoveButton />);
component.find('div').simulate('click');
expect(mock).toHaveBeenCalled();
mock.mockRestore();
});
});

请注意,要模拟remove,您需要将其导出,并且需要将模块导入回自身并在组件中使用导入。

话虽如此,我同意将 remove 作为 prop 传入是一种更好的方法。它更容易测试,并使您的组件更可重用。

关于reactjs - 功能组件中的 Jest/ enzyme 模拟功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51756316/

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