【发布时间】:2019-08-19 18:07:29
【问题描述】:
我正在使用 Jest 和 Enzyme 编写组件测试。
被测组件使用了一个名为 Service 的类的导入静态方法,该类直接调度到 store。
组件本身,在componentDidMount 中调用两个Service 类元素,但也在组件的其他部分:
@connect(
(state) => ({
feedback: getFeedback(state),
reportsLeft: getReportsLeft(state),
reported: getReports(state),
newRecordsLeft: getNewRecordsLeft(state),
}),
)
class Feedback extends React.Component<IFeedbackProps> {
componentDidMount() {
Service.updateReportsLeft(); //static async
Service.updateNewRecordsLeft(); //static async
}
getCount(elementsLeft?: number): string {
return elementsLeft === 0 ? 'Done' : `${elementsLeft} left`;
}
handleShowNext = (e: Event) => {
e.preventDefault();
Service.goToNextReport(); //static
};
renderShowNext() {
const {reported} = this.props;
const buttonText = 'Go to next';
const {reportsLeft} = this.props;
// @ts-ignore
return reportsLeft > 0 ? <a href="#" onClick={this.handleShowNext}>{buttonText} </a> : null;
}
render() {
const {reportsLeft, newRecordsLeft} = this.props;
return (
<div>
<p>Feedback: {this.getCount(reportsLeft)} {this.renderShowNext()}</p>
<p>New: {this.getCount(newRecordsLeft)} </p>
</div>
);
}
}
export default Feedback;
我尝试用一个简单的 mock 来模拟这四个类方法,后来甚至尝试测试组件上最简单的 toBe 元素:
function setup() {
//Also tested an approach with the function contents simply loading before the `describe` methods
const
testReportsLeft: number = 447,
testNewRecordsLeft: number = 778,
testFeedback = null,
testReported = null;
const props: IFeedbackProps = {
reportsLeft: testReportsLeft,
feedback: testFeedback,
reported: testReported,
newRecordsLeft: testNewRecordsLeft,
};
jest.mock('Services/service', () => ({
goToNextReport: jest.fn(),
updateReportsLeft: jest.fn(),
updateNewRecordsLeft: jest.fn(),
getCurrentState: jest.fn(),
})
);
const feedback = shallow(<Feedback {...props} />);
return feedback;
}
describe('Feedback', () => {
describe('component view tests', () => {
it('should render a div', () => {
const feedback = setup();
//This test is wrong in this part, I know. But for now its the reaching of this point that causes issues :/
expect(feedback).toBe('div');
})
})
});
但是,在运行测试时,我收到一条错误消息:
TypeError:无法读取未定义的属性“产品”
错误跟踪如下:
...Resources/public/js/admin-react-js/store/reducers.ts
...Resources/public/js/admin-react-js/store/index.ts
...Resources/public/js/admin-react-js/services/service.ts:41:31
...Resources/public/js/admin-react-js/sidebar/feedback.tsx:34:51
...Resources/public/js/admin-react-js/sidebar/_test_/feedback.spec.tsx:27:43)
因此,如您所见,路径直接回到减速器。这是我希望避免的,因此为函数添加了模拟。
我不确定这段代码可能有什么问题,而且互联网正在慢慢停止了解可能出现的问题。
我们将不胜感激。
另外,如果提供的资源不够,请告诉我。
JEST 版本是21.2.1。不幸的是,由于该软件包与我正在使用的另一个软件包紧密相连,我无法更改它(版本)。
【问题讨论】:
-
你有一个 repo 来测试这个问题吗?
-
添加你的 reducers.ts 文件,你正在尝试在未定义的地方做某事。产品