Класс React Component - это просто класс JavaScript, мы можем тестировать методы класса напрямую, используя Class.prototype.method
без использования утилит, связанных с React.
index.tsx
:
import React, { Component } from 'react';
class ContactBox extends Component {
emailCaptureRef;
constructor(props) {
super(props);
this.state = { email_box_used: false };
}
addEmail(event) {
event.stopPropagation();
event.preventDefault();
const email = this.emailCaptureRef.current.value;
const domain = 'https://somedomain.com/';
fetch(domain + 'newsletter/sign_up', {
method: 'POST',
body: JSON.stringify({ _method: 'POST', email }),
}).then((response) => {
return response.json().then((result) => {
this.setState({ email_box_used: true });
});
});
}
render() {
return (
<div>
<form onSubmit={this.addEmail}></form>
</div>
);
}
}
export default ContactBox;
index.test.tsx
:
import ContactBox from './';
const whenStable = () => new Promise((resolve) => setTimeout(resolve));
describe('60403489', () => {
it('should add email', async () => {
const mResponse = { json: jest.fn().mockResolvedValueOnce({}) };
const mFetch = jest.fn().mockResolvedValueOnce(mResponse);
(global as any).fetch = mFetch;
const setStateSpy = jest.spyOn(ContactBox.prototype, 'setState').mockReturnValueOnce();
const mEvent = { stopPropagation: jest.fn(), preventDefault: jest.fn() };
ContactBox.prototype.emailCaptureRef = { current: { value: 'example@gmail.com' } };
ContactBox.prototype.addEmail(mEvent);
await whenStable();
expect(mFetch).toBeCalledWith('https://somedomain.com/newsletter/sign_up', {
method: 'POST',
body: JSON.stringify({ _method: 'POST', email: 'example@gmail.com' }),
});
expect(mResponse.json).toBeCalledTimes(1);
expect(setStateSpy).toBeCalledWith({ email_box_used: true });
});
});
результаты модульных испытаний с отчетом о покрытии:
PASS stackoverflow/60403489/index.test.tsx
60403489
✓ should add email (8ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 83.33 | 0 | 66.67 | 81.25 |
index.tsx | 83.33 | 0 | 66.67 | 81.25 | 6,7,26
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.822s, estimated 10s
исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60403489