Skip to content

Instantly share code, notes, and snippets.

@monkpit
Last active August 24, 2021 16:50
Show Gist options
  • Save monkpit/b3f382d3623b3359cd5fcb002ce51930 to your computer and use it in GitHub Desktop.
Save monkpit/b3f382d3623b3359cd5fcb002ce51930 to your computer and use it in GitHub Desktop.
Cypress cy.session command
const testUrl = 'https://todomvc.com/examples/typescript-react/';
const todos = {
A: ['foo', 'bar', 'baz'],
B: ['1', '2', '3']
};
const getTodos = () => cy.get('ul.todo-list li');
const addTodo = (text) => cy.get('input.new-todo').type(`${text}{enter}`);
const validateTodos = (todos) => getTodos()
.should('have.length', todos.length)
.each($todo => {
const todoText = $todo.text();
expect(todos).to.contain(todoText);
});
const stageTodos = (todos, url = testUrl) => {
cy.session(todos, () => {
cy.visit(url);
todos.forEach(addTodo);
}, {
validate() {
cy.visit(url);
validateTodos(todos);
}
});
cy.visit(url);
}
const removeTodo = (todo) => getTodos().each($todo => {
const todoText = $todo.text();
if (todoText === todo) {
cy.wrap($todo).find('button.destroy').click({ force: true });
}
});
const addTodosTest = ([name, todos]) => it(`can add a todo to dataset ${name}`, () => {
stageTodos(todos);
const newTodo = 'quux';
addTodo(newTodo);
validateTodos([...todos, newTodo]);
});
const deleteTodosTest = ([name, todos]) => it(`can delete a todo from dataset ${name}`, () => {
stageTodos(todos);
removeTodo(todos[0]);
const [_, ...remainingTodos] = todos;
validateTodos(remainingTodos);
});
const validateTodosTest = ([name, todos]) => it(`can validate todos from dataset ${name}`, () => {
stageTodos(todos);
validateTodos(todos);
})
const multiTest = (datasets) => (test) => Object.entries(datasets).forEach(test);
const tests = [
addTodosTest,
deleteTodosTest
];
describe('Cypress session', () => {
tests.forEach(multiTest(todos));
});
@monkpit
Copy link
Author

monkpit commented Aug 24, 2021

This will alternate back and forth between datasets A and B (or any that are added) and run tests against each one in order...
Ex: if we have tests [1,2,3] and datasets [a,b] then we will run: 1a, 1b, 2a, 2b, 3a, 3b. I wanted to alternate so it would verify that cy.session is behaving as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment