Our functions generally embody options that permit customers to pick out recordsdata from their onerous drives, and a few functionalities would possibly let customers obtain recordsdata. Implementing Finish-to-Finish assessments that make sure that every thing works as anticipated may not appear simple at first.
On this article, we create a easy React software that lets customers select a JSON file from their machine and obtain a formatted model. Then, we use Playwright to check the file enter and confirm if the downloaded file is appropriate.
An software that codecs JSON recordsdata
To start out, let’s create a element with a file enter.
JsonFormatter.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import { useJsonFormatter } from ‘./useJsonFormatter’;
export const JsonFormatter = () => { const { handleJsonFile, error } = useJsonFormatter();
return ( <div model={{ show: ‘flex’, flexDirection: ‘column’, }} > <label htmlFor=“json-file-input”>Select a legitimate JSON file</label> <enter id=“json-file-input” sort=“file” onChange={handleJsonFile} /> {error && ( <p data-testid=“error-message” model={{ coloration: ‘purple’ }}> {error} </p> )} </div> ); }; |
Underneath the hood, we extract the textual content from the chosen file and parse it as JSON. Then, we format it and ship it again to the person.
useJsonFormatter.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import { ChangeEvent, useState } from ‘react’;
export operate useJsonFormatter() { const [error, setError] = useState<null | string>(null);
const formatTextAsJson = (textual content: string) => { const knowledge = JSON.parse(textual content); return JSON.stringify(knowledge, null, 2); };
const downloadJson = (formattedJson: string, fileName: string) => { const anchor = doc.createElement(‘a’); const blob = new Blob([formattedJson], { sort: ‘software/json’ }); const url = URL.createObjectURL(blob);
anchor.setAttribute(‘href’, url); anchor.setAttribute(‘obtain’, `${fileName}_formatted`); anchor.click on(); };
const handleJsonFile = async (occasion: ChangeEvent<HTMLInputElement>) => { const selectedFile = occasion.goal.recordsdata?.[0]; setError(null);
if (!selectedFile) { return; }
strive { const textFromFile = await selectedFile.textual content(); const formattedJson = formatTextAsJson(textFromFile);
downloadJson(formattedJson, selectedFile.title); } catch { setError(‘The offered file doesn’t include legitimate JSON’); } occasion.goal.worth = ”; };
return { handleJsonFile, error, }; } |
If the person supplies a sound JSON file, they get a formatted model with the identical file title.
If the person selects an invalid file, we show the error message.
Getting ready the required recordsdata
To check our software, we should put together two recordsdata – one with legitimate JSON and one with invalid knowledge. Let’s put them within the listing known as
assets within the
assessments folder.
assessments/assets/knowledge.json
assessments/assets/invalidData.txt
Interacting with the file enter
To work together with the file enter by way of our Finish-to-Finish assessments, we should first find it on the web page. One of many simple methods of doing that’s to search out it by way of the label textual content.
web page.getByLabel(‘Select a sound JSON file’) |
Now, we should present the trail to our recordsdata with the
setInputFiles operate. A method is to offer a relative path to the file. The trail can be resolved relative to the present working listing containing our
package deal.json file.
await web page .getByLabel(‘Select a sound JSON file’) .setInputFiles(‘./assessments/assets/knowledge.json’); |
We will use the above to check what occurs when the person supplies each legitimate and invalid recordsdata.
JsonFormatter.check.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import { anticipate, check } from ‘@playwright/check’;
check.describe(‘When the person visits the web page’, () => { check.beforeEach(async ({ web page }) => { await web page.goto(‘/’); });
check.describe(‘and supplies an invalid file’, () => { check.beforeEach(async ({ web page }) => { await web page .getByLabel(‘Select a sound JSON file’) .setInputFiles(‘./assessments/assets/invalidData.txt’); }); check(‘it ought to show an error message’, async ({ web page }) => { await anticipate(web page.getByTestId(‘error-message’)).toBeVisible(); }); });
check.describe(‘and supplies a sound file’, () => { check.beforeEach(async ({ web page }) => { await web page .getByLabel(‘Select a sound JSON file’) .setInputFiles(‘./assessments/assets/knowledge.json’); }); check(‘it mustn’t show an error message’, async ({ web page }) => { await anticipate(web page.getByTestId(‘error-message’)).not.toBeVisible(); }); }); }); |
To make use of
web page.goto(‘/’) with out offering the complete URL we have to have the
baseURL configuration arrange. If you wish to know extra, try JavaScript testing #17. Introduction to Finish-to-Finish testing with Playwright
Testing the title of the downloaded file
Each time the browser downloads a file, Playwright emits an occasion. To start out listening for it, we have to name the
waitForEvent operate, which returns a promise.
let downloadedFile: Obtain; check.beforeEach(async ({ web page }) => { const downloadedFilePromise = web page.waitForEvent(‘obtain’); await web page .getByLabel(‘Select a sound JSON file’) .setInputFiles(‘./assessments/assets/knowledge.json’); downloadedFile = await downloadedFilePromise; }); |
The essential facet is to begin ready for the occasion earlier than the browser downloads the file, however don’t use the
await key phrase till it’s downloaded.
Now, we will use the
suggestedFilename operate to check if the downloaded file’s title is appropriate.
JsonFormatter.check.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import { Obtain, anticipate, check } from ‘@playwright/check’;
check.describe(‘When the person visits the web page’, () => { // … check.describe(‘and supplies a sound file’, () => { let downloadedFile: Obtain; check.beforeEach(async ({ web page }) => { const downloadedFilePromise = web page.waitForEvent(‘obtain’); await web page .getByLabel(‘Select a sound JSON file’) .setInputFiles(‘./assessments/assets/knowledge.json’); downloadedFile = await downloadedFilePromise; });
check(‘it ought to obtain a file with the right title’, async () => { const title = downloadedFile.suggestedFilename(); anticipate(title).toEqual(‘knowledge.json’); }); // … }); }); |
Checking the contents of the file
We additionally need to verify if our software accurately formatted the JSON file. We have to use the
createReadStream operate that returns a learn stream to try this.
If you wish to know extra about streams in Node.js, try Node.js TypeScript #4. Paused and flowing modes of a readable stream
Playwright assessments run in a Node.js atmosphere. Because of that, we will use numerous APIs constructed into Node.js. Essentially the most simple means of studying the stream is to make use of the
textual content operate from
node:stream/shoppers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import { Obtain, anticipate, check } from ‘@playwright/check’; import { textual content } from ‘node:stream/shoppers’;
check.describe(‘When the person visits the web page’, () => { // … check.describe(‘and supplies a sound file’, () => { let downloadedFile: Obtain; check.beforeEach(async ({ web page }) => { const downloadedFilePromise = web page.waitForEvent(‘obtain’); await web page .getByLabel(‘Select a sound JSON file’) .setInputFiles(‘./assessments/assets/knowledge.json’); downloadedFile = await downloadedFilePromise; });
check(‘it ought to obtain a file with the formatted JSON’, async () => { const fileStream = await downloadedFile.createReadStream(); const consequence = await textual content(fileStream);
anticipate(consequence).toEqual(‘{n “key”: “worth”n}’); }); // … }); }); |
Abstract
On this article, we’ve realized find out how to use Playwright to put in writing Finish-to-Finish assessments to confirm options that embody coping with recordsdata. This included studying find out how to simulate selecting a file from the onerous drive. In addition to that, we additionally realized find out how to confirm downloaded recordsdata by checking their names and content material to make sure they include the right knowledge. Fortuitously, Playwright makes working with recordsdata very simple.