对于SO的问题,我已经找到了很多解决方案,但是我无法从这些答案中获得相同的结果。
我试图测试单击按钮时特定功能是否运行。我的按钮看起来像这样。
<button id='send-project-manager-email-button' className={styles.sendEmail} onClick={()=>sendEmail()}>
Resend Email
</button>
我正在尝试使用模拟功能对此进行测试:
it('renders disabled button', () => {
const mockFn = jest.fn()
const wrapper = mount(<SendProjectManagerEmail sendEmail={mockFn}/>);
const button = wrapper.find('#send-project-manager-email-button');
button.simulate('click')
expect(mockFn).toHaveBeenCalledTimes(1)
})
我尝试了其他方法中出现的多种变体,但是我总是发现mockFn
被调用了0次。
答案 0 :(得分:0)
这是单元测试的工作示例:
index.tsx
:
import React from 'react';
const styles = {
sendEmail: 'sendEmail'
};
export const SendProjectManagerEmail = ({ sendEmail }) => {
return (
<button id="send-project-manager-email-button" className={styles.sendEmail} onClick={() => sendEmail()}>
Resend Email
</button>
);
};
index.spec.tsx
:
import { SendProjectManagerEmail } from './';
import { mount } from 'enzyme';
import React from 'react';
describe('SendProjectManagerEmail', () => {
it('renders disabled button', () => {
const mockFn = jest.fn();
const wrapper = mount(<SendProjectManagerEmail sendEmail={mockFn} />);
const button = wrapper.find('#send-project-manager-email-button');
button.simulate('click');
expect(mockFn).toHaveBeenCalledTimes(1);
});
});
覆盖率100%的单元测试结果:
PASS src/stackoverflow/58808783/index.spec.tsx
SendProjectManagerEmail
✓ renders disabled button (201ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.604s, estimated 10s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58808783