diff --git a/packages/api-explorer/__tests__/CopyCode.test.jsx b/packages/api-explorer/__tests__/CopyCode.test.jsx new file mode 100644 index 000000000..bbfdf4db1 --- /dev/null +++ b/packages/api-explorer/__tests__/CopyCode.test.jsx @@ -0,0 +1,37 @@ +const React = require('react'); +const { mount } = require('enzyme'); + +const CopyCode = require('../src/CopyCode'); + +const curl = `curl --request POST \ +--url http://petstore.swagger.io/v2/pet \ +--header 'Authorization: Bearer 123' \ +--header 'Content-Type: application/json'`; + +// `react-copy-to-clipboard` uses this when copying text to the clipboard so we need to mock it out or else we'll get +// errors in the test. +window.prompt = () => {}; + +test('should copy a snippet to the clipboard', () => { + const onCopy = jest.fn(); + + const node = mount(); + + node.find('button').simulate('click'); + + expect(onCopy).toHaveBeenCalledWith(curl); +}); + +test('should update the code to copy when supplied with a new snippet', () => { + const onCopy = jest.fn(); + + const node = mount(); + + node.find('button').simulate('click'); + expect(onCopy).toHaveBeenCalledWith(curl); + + node.setProps({ code: 'console.log()' }); + + node.find('button').simulate('click'); + expect(onCopy).toHaveBeenCalledWith('console.log()'); +}); diff --git a/packages/api-explorer/src/CopyCode.jsx b/packages/api-explorer/src/CopyCode.jsx index d67270842..45e374e3d 100644 --- a/packages/api-explorer/src/CopyCode.jsx +++ b/packages/api-explorer/src/CopyCode.jsx @@ -13,15 +13,18 @@ class CopyCode extends React.Component { this.onCopy = this.onCopy.bind(this); } - componentDidUpdate(prevProps) { - const code = typeof prevProps.code === 'function' ? prevProps.code() : prevProps.code; - - if (code !== this.state.code) { - this.setState({ code }); + static getDerivedStateFromProps(props, state) { + const code = typeof props.code === 'function' ? props.code() : props.code; + if (!('code' in state) || code !== state.code) { + return { code }; } + + return null; } - onCopy() { + onCopy(text) { + this.props.onCopy(text); + this.setState({ copied: true }); setTimeout(() => { this.setState({ copied: false }); @@ -41,6 +44,11 @@ class CopyCode extends React.Component { CopyCode.propTypes = { code: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired, + onCopy: PropTypes.func, +}; + +CopyCode.defaultProps = { + onCopy: () => {}, }; module.exports = CopyCode;