我已经找到了许多关于我的问题的解决方案,但是我不能从这些答案中获得相同的结果。
我正在尝试测试当一个按钮被点击时,一个特定的函数是否会运行。我的按钮看起来像这样。
<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)
})我已经尝试了它在其他SO问题中出现的多种变体,但是我总是发现mockFn被调用了0次。
发布于 2019-11-12 09:12:45
下面是一个单元测试的工作示例:
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
https://stackoverflow.com/questions/58808783
复制相似问题