basarat / basarat/typescript-book

Controlling mobx style `appState` from cypress tests

Open
#441 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
21.6k
Forks
2.6k
PR merge metrics
No merged PRs in 30d

Description

Courtesy : @Rebvado :rose:

* SETUP ONCE (app code): In your application code store `appState` on window when running under cypress.

```ts
export const appState = new AppState();

if ((global as any).Cypress) {
(global as any).appState = appState
}
```
* SETUP ONCE (test code): Create a `appStateUtil.ts` to load `appState` into a cypress context. If a test is running without loading a running version of the app (e.g. a unit test), then we just defer to loading the `appState` directly.

```ts
import { appState as INTERNAL_STATE, AppState } from "../../../app/state/appState";
export let appState!: AppState;
/**
* Either loads appState from window for e2e tests
* Or the imported one for unit tests
*/
export const loadAppState = () => {
cy.window().then(global => {
appState = (global as any).appState;
if (!appState) {
appState = INTERNAL_STATE;
}
});
}
```

* USE in e2e test:

```ts
import { appState } from './appStateUtil';

beforeEach(() => {
cy.visit('http://localhost:8080'); // Some url for your e2e test
loadAppState();
})

it('should work', () => {
appState.directlyMoveToSomeState();
})
```

* USE in unit test (without the need to *visit* the app):

```ts
import { appState } from './appStateUtil';

beforeEach(() => {
loadAppState();
})

it('should work', () => {
appState.directlyMoveToSomeState();
})
```

# More

You can create utilities around `appState` that work in *both* `full e2e` and `unit tests` by using `appState` from `testUtil` e.g.

```ts
import { appState } from '../appStateUtil';
async function fillSomeForm() {
await appState.doSomething();
await appState.doSomethingElse();
// etc.
}
```

Contributor guide

Open the contributing guide

Research direction

Start by locating the book's relevant Cypress or testing entry point, then review the app/state/appState path and the appStateUtil.ts pattern shown in the issue. Done means the appState setup and usage for both end-to-end and unit tests are documented in the appropriate place, with the intended scope confirmed.

Written by the indexing model from the issue text.

Assessment

Tech stack
cypress, typescript
Domain
documentation, testing-qa
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.