我使用jest
和enzyme
來測試我的反應組件,它依賴於antd
- 第三個反應UI庫。 爲了便於說明,我生成了足夠公平的最小代碼來顯示我的問題。正確的單元測試方法反應組件
見我test
成分如下:
import React from 'react';
import { Button } from 'antd';
function Test({onSubmit}) {
return (
<div>
<Button htmlType="submit" type="primary" />
</div>
);
}
export default Test;
Q1:我嘲笑了按鈕,如下由於單元測試需要我們分離目標和模擬的任何其他依賴。 這是正確的嗎?
__mocks__
antd.js
antd.js
import mockComponent from '../mockComponent';
const list = [
'Form',
'Input',
'Button',
'Spin',
'Icon'
];
const mockups = list.reduce((prev, next) => {
prev[next] = mockComponent(next);
return prev;
}, {});
mockups.Form.Item = mockComponent('Form.Item');
export const Form = mockups.Form;
export const Input = mockups.Input;
export const Button = mockups.Button;
export const Spin = mockups.Spin;
export const Icon = mockups.Icon;
mockComponent.js
import React from 'react';
export default function mockComponent (name) {
return props => React.createElement(name, props, props.children);
}
Q2。即使測試通過,我也會收到以下警告。我該如何解決這個問題?
test.spec.js
import React from 'react';
import { shallow, mount } from 'enzyme';
import renderer from 'react-test-renderer';
import Test from '../components/question';
describe('mount test',() => {
let wrapper;
let props;
let mountedLogin;
const test =() => {
if (!mountedLogin) {
mountedLogin = mount(<Test {...props} />);
}
return mountedLogin;
};
beforeEach(() => {
mountedLogin = null;
});
it('always render test as the root',() => {
const divs = test().find('div');
expect(divs.length).toBeGreaterThan(0);
});
});
警告
console.error node_modules/fbjs/lib/warning.js:36
Warning: Unknown prop `htmlType` on <Button> tag. Remove this prop from the
element. For details, see
in Button (created by Unknown)
in Unknown (created by Test)
in div (created by Test)
in Test (created by WrapperComponent)
in WrapperComponent
一個側面說明,我沒有在我的package.json
有任何jest
CONFIGS。
任何人都可以幫助我與這些。
非常感謝
真的很感謝你的回答。你拯救我的一天! –