Monday, September 16, 2024
HomeNetflixIntroducing SafeTest: A Novel Method to Entrance Finish Testing | by Netflix...

Introducing SafeTest: A Novel Method to Entrance Finish Testing | by Netflix Expertise Weblog | Feb, 2024

[ad_1]

by Moshe Kolodny

On this submit, we’re excited to introduce SafeTest, a revolutionary library that gives a recent perspective on Finish-To-Finish (E2E) exams for web-based Consumer Interface (UI) functions.

Historically, UI exams have been carried out by both unit testing or integration testing (additionally known as Finish-To-Finish (E2E) testing). Nonetheless, every of those strategies presents a singular trade-off: you must select between controlling the check fixture and setup, or controlling the check driver.

As an illustration, when utilizing react-testing-library, a unit testing resolution, you keep full management over what to render and the way the underlying providers and imports ought to behave. Nonetheless, you lose the flexibility to work together with an precise web page, which might result in a myriad of ache factors:

  • Issue in interacting with complicated UI parts like <Dropdown /> parts.
  • Lack of ability to check CORS setup or GraphQL calls.
  • Lack of visibility into z-index points affecting click-ability of buttons.
  • Complicated and unintuitive authoring and debugging of exams.

Conversely, utilizing integration testing instruments like Cypress or Playwright offers management over the web page, however sacrifices the flexibility to instrument the bootstrapping code for the app. These instruments function by remotely controlling a browser to go to a URL and work together with the web page. This method has its personal set of challenges:

  • Issue in making calls to an alternate API endpoint with out implementing customized community layer API rewrite guidelines.
  • Lack of ability to make assertions on spies/mocks or execute code inside the app.
  • Testing one thing like darkish mode entails clicking the theme switcher or understanding the localStorage mechanism to override.
  • Lack of ability to check segments of the app, for instance if a element is just seen after clicking a button and ready for a 60 second timer to countdown, the check might want to run these actions and shall be at the very least a minute lengthy.

Recognizing these challenges, options like E2E Element Testing have emerged, with choices from Cypress and Playwright. Whereas these instruments try and rectify the shortcomings of conventional integration testing strategies, they produce other limitations as a consequence of their structure. They begin a dev server with bootstrapping code to load the element and/or setup code you need, which limits their capability to deal with complicated enterprise functions which may have OAuth or a posh construct pipeline. Furthermore, updating TypeScript utilization might break your exams till the Cypress/Playwright workforce updates their runner.

SafeTest goals to handle these points with a novel method to UI testing. The primary thought is to have a snippet of code in our utility bootstrapping stage that injects hooks to run our exams (see the How Safetest Works sections for more information on what that is doing). Word that how this works has no measurable affect on the common utilization of your app since SafeTest leverages lazy loading to dynamically load the exams solely when working the exams (within the README instance, the exams aren’t within the manufacturing bundle in any respect). As soon as that’s in place, we are able to use Playwright to run common exams, thereby reaching the best browser management we would like for our exams.

This method additionally unlocks some thrilling options:

  • Deep linking to a selected check with no need to run a node check server.
  • Two-way communication between the browser and check (node) context.
  • Entry to all of the DX options that include Playwright (excluding those that include @playwright/check).
  • Video recording of exams, hint viewing, and pause web page performance for attempting out completely different web page selectors/actions.
  • Capability to make assertions on spies within the browser in node, matching snapshot of the decision inside the browser.

SafeTest is designed to really feel acquainted to anybody who has carried out UI exams earlier than, because it leverages the very best components of present options. Right here’s an instance of how one can check a whole utility:

import { describe, it, anticipate } from 'safetest/jest';
import { render } from 'safetest/react';

describe('my app', () => {
it('hundreds the primary web page', async () => {
const { web page } = await render();

await anticipate(web page.getByText('Welcome to the app')).toBeVisible();
anticipate(await web page.screenshot()).toMatchImageSnapshot();
});
});

We will simply as simply check a selected element

import { describe, it, anticipate, browserMock } from 'safetest/jest';
import { render } from 'safetest/react';

describe('Header element', () => {
it('has a traditional mode', async () => {
const { web page } = await render(<Header />);

await anticipate(web page.getByText('Admin')).not.toBeVisible();
});

it('has an admin mode', async () => {
const { web page } = await render(<Header admin={true} />);

await anticipate(web page.getByText('Admin')).toBeVisible();
});

it('calls the logout handler when signing out', async () => {
const spy = browserMock.fn();
const { web page } = await render(<Header handleLogout={spy} />);

await web page.getByText('logout').click on();
anticipate(await spy).toHaveBeenCalledWith();
});
});

SafeTest makes use of React Context to permit for worth overrides throughout exams. For an instance of how this works, let’s assume we’ve a fetchPeople operate utilized in a element:

import { useAsync } from 'react-use';
import { fetchPerson } from './api/individual';

export const Individuals: React.FC = () => {
const { information: individuals, loading, error } = useAsync(fetchPeople);

if (loading) return <Loader />;
if (error) return <ErrorPage error={error} />;
return <Desk information={information} rows=[...] />;
}

We will modify the Individuals element to make use of an Override:

 import { fetchPerson } from './api/individual';
+import { createOverride } from 'safetest/react';

+const FetchPerson = createOverride(fetchPerson);

export const Individuals: React.FC = () => {
+ const fetchPeople = FetchPerson.useValue();
const { information: individuals, loading, error } = useAsync(fetchPeople);

if (loading) return <Loader />;
if (error) return <ErrorPage error={error} />;
return <Desk information={information} rows=[...] />;
}

Now, in our check, we are able to override the response for this name:

const pending = new Promise(r => { /* Do nothing */ });
const resolved = [{name: 'Foo', age: 23], {title: 'Bar', age: 32]}];
const error = new Error('Whoops');

describe('Individuals', () => {
it('has a loading state', async () => {
const { web page } = await render(
<FetchPerson.Override with={() => () => pending}>
<Individuals />
</FetchPerson.Override>
);

await anticipate(web page.getByText('Loading')).toBeVisible();
});

it('has a loaded state', async () => {
const { web page } = await render(
<FetchPerson.Override with={() => async () => resolved}>
<Individuals />
</FetchPerson.Override>
);

await anticipate(web page.getByText('Consumer: Foo, title: 23')).toBeVisible();
});

it('has an error state', async () => {
const { web page } = await render(
<FetchPerson.Override with={() => async () => { throw error }}>
<Individuals />
</FetchPerson.Override>
);

await anticipate(web page.getByText('Error getting customers: "Whoops"')).toBeVisible();
});
});

The render operate additionally accepts a operate that shall be handed the preliminary app element, permitting for the injection of any desired parts wherever within the app:

it('has a individuals loaded state', async () => {
const { web page } = await render(app =>
<FetchPerson.Override with={() => async () => resolved}>
{app}
</FetchPerson.Override>
);
await anticipate(web page.getByText('Consumer: Foo, title: 23')).toBeVisible();
});

With overrides, we are able to write complicated check circumstances akin to guaranteeing a service technique which mixes API requests from /foo, /bar, and /baz, has the right retry mechanism for simply the failed API requests and nonetheless maps the return worth accurately. So if /bar takes 3 makes an attempt to resolve the strategy will make a complete of 5 API calls.

Overrides aren’t restricted to simply API calls (since we are able to use additionally use web page.route), we are able to additionally override particular app stage values like characteristic flags or altering some static worth:

+const UseFlags = createOverride(useFlags);
export const Admin = () => {
+ const useFlags = UseFlags.useValue();
const { isAdmin } = useFlags();
if (!isAdmin) return <div>Permission error</div>;
// ...
}

+const Language = createOverride(navigator.language);
export const LanguageChanger = () => {
- const language = navigator.language;
+ const language = Language.useValue();
return <div>Present language is { language } </div>;
}

describe('Admin', () => {
it('works with admin flag', async () => {
const { web page } = await render(
<UseIsAdmin.Override with={oldHook => {
const oldFlags = oldHook();
return { ...oldFlags, isAdmin: true };
}}>
<MyComponent />
</UseIsAdmin.Override>
);

await anticipate(web page.getByText('Permission error')).not.toBeVisible();
});
});

describe('Language', () => {
it('shows', async () => {
const { web page } = await render(
<Language.Override with={previous => 'abc'}>
<MyComponent />
</Language.Override>
);

await anticipate(web page.getByText('Present language is abc')).toBeVisible();
});
});

Overrides are a robust characteristic of SafeTest and the examples right here solely scratch the floor. For extra data and examples, confer with the Overrides part on the README.

SafeTest comes out of the field with highly effective reporting capabilities, akin to computerized linking of video replays, Playwright hint viewer, and even deep hyperlink on to the mounted examined element. The SafeTest repo README hyperlinks to all of the instance apps in addition to the reviews

Image of SafeTest report showing a video of a test run

Many giant companies want a type of authentication to make use of the app. Sometimes, navigating to localhost:3000 simply ends in a perpetually loading web page. You’ll want to go to a unique port, like localhost:8000, which has a proxy server to examine and/or inject auth credentials into underlying service calls. This limitation is among the primary causes that Cypress/Playwright Element Checks aren’t appropriate to be used at Netflix.

Nonetheless, there’s often a service that may generate check customers whose credentials we are able to use to log in and work together with the appliance. This facilitates creating a light-weight wrapper round SafeTest to robotically generate and assume that check consumer. As an illustration, right here’s mainly how we do it at Netflix:

import { setup } from 'safetest/setup';
import { createTestUser, addCookies } from 'netflix-test-helper';

kind Setup = Parameters<typeof setup>[0] & {
extraUserOptions?: UserOptions;
};

export const setupNetflix = (choices: Setup) => {
setup({
...choices,
hooks: { beforeNavigate: [async page => addCookies(page)] },
});

beforeAll(async () => {
createTestUser(choices.extraUserOptions)
});
};

After setting this up, we merely import the above bundle rather than the place we might have used safetest/setup.

Whereas this submit centered on how SafeTest works with React, it’s not restricted to simply React. SafeTest additionally works with Vue, Svelte, Angular, and even can run on NextJS or Gatsby. It additionally runs utilizing both Jest or Vitest primarily based on which check runner your scaffolding began you off with. The examples folder demonstrates how one can use SafeTest with completely different tooling mixtures, and we encourage contributions so as to add extra circumstances.

At its core, SafeTest is an clever glue for a check runner, a UI library, and a browser runner. Although the commonest utilization at Netflix employs Jest/React/Playwright, it’s simple so as to add extra adapters for different choices.

SafeTest is a robust testing framework that’s being adopted inside Netflix. It permits for straightforward authoring of exams and offers complete reviews when and the way any failures occurred, full with hyperlinks to view a playback video or manually run the check steps to see what broke. We’re excited to see the way it will revolutionize UI testing and sit up for your suggestions and contributions.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments