Testing Cheatsheet
11 playbook/playbook
Jest
jest.spyOn(dbClient, 'getData').mockImplementation(()=>data)
Mocking 3rd party apis:β
Mock the whole library:
jest.mock('@aws-sdk/client-comprehend-node/ComprehendClient')
- This mocks the whole library, for example on your code:const comprehend = new ComprehendClient({region: "ap-southeast-2"});
Still import your actual library in your test:
const {ComprehendClient} = require("@aws-sdk/client-comprehend-node/ComprehendClient");
On your test automatic mocks are accessible (both instance and method):
expect(ComprehendClient).toHaveBeenCalledTimes(1);
const instance = ComprehendClient.mock.instances[0];
expect(instance.send).toHaveBeenCalledTimes(1)
Mocking specificβ
- Repeat steps 1, 2 from above then on each test:
ComprehendClient.mockImplementation(() => {
return {
send: () => actualResponse
}
});
Simple Screen Reactβ
import {render, screen} from '@testing-library/react'
import {SimpleForm} from "./simpleForm";
describe('simpleForm', function () {
it('should run', function () {
});
it('should have text field and submit button', function () {
render(<SimpleForm/>)
const field = screen.getByText('enter field')
expect(field).toBeTruthy()
});
});
Changing the state front endβ
render(<SimpleForm/>);
await act(async () => {
userEvent.type(screen.getByRole('textbox'), 'Hello World!')
userEvent.click(screen.getByRole('button'))
})
expect(screen.getByText('queued')).toBeInTheDocument();
Mocking Fetch APIβ
Automatic Fetch Mocks:
- Import
import fetchMock from "jest-fetch-mock"
- Global:
fetchMock.enableMocks()
- Before Each
fetchMock.doMock();
- Finally Mock:
fetch.mockResponse(JSON.stringify(sampleResponse))
AWS Notes:
Checking if AWS credentials has been setup:
const getAWSCredentials = () => {
AWS.config.getCredentials(function (err) {
if (err) console.log(err.stack);
else {
console.log("Access key:", AWS.config.credentials.accessKeyId);
}
});
}
Node end to end notes:
npx express-generator
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
npm install cors()
const app = express();
app.use(cors())
API Gateway
- API Key Request needs the following headers:
const headers = {
crossDomain: true,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-API-Key': ''
}
}
- Publish API to stage to enable access to URL
HTTP input stream (Backend)
whenever(request.inputStream).thenReturn(DelegatingServletInputStream(ByteArrayInputStream(validPayload.toByteArray())))
String json = "{\"id\":213213213, \"amount\":222}";
when(request.getInputStream()).thenReturn(
new DelegatingServletInputStream(
new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))));
when(request.getReader()).thenReturn(
new BufferedReader(new StringReader(json)));
when(request.getContentType()).thenReturn("application/json");
when(request.getCharacterEncoding()).thenReturn("UTF-8");
```