Thinking About Introducing E2E Tests

Frontend testing approaches

  • Jest: check function behavior, as in priceOptionsfactory.spec.ts

  • Snapshot tests: UI tests (it might be useful to take screenshots of every page and run snapshot tests. → I think this would be good for spotting errors after changing styles.)

  • Cypress: user flow tests based on the product policy documents

  • Start writing tests for features added from now on.

  • Start by writing tests alongside feature development.

  • Do not add them to CI/CD for now: they take a long time, so run them manually before deployment until the process is established.

  • How can I write useful tests that actually catch bugs? ?-?


Why introduce Cypress: the limitations of Jest

Trying tests with Jest made me wonder where to draw the test boundaries. Mock functions are essential, which seems to make it difficult to test how features actually behave. Creating an environment where a view model works in Jest is particularly hard.

E2E tests seem useful for testing UI and frontend functionality together.

What I learned from struggling with Jest.

Testing only the view: I need dummy versions of the actions and commands in the view model.

Testing the view model: I need dummy versions of its imports.

It never fully runs.

It is difficult to fully test the login logic.

  • Should I load mock data or call the real commands?

With mock data: it may differ from the real API → less accurate tests. I also have to build mocks → cumbersome.

With real commands: what about the token when login is required???

  • Testing productdetailviewmodel

The error: useStore must be used within a StoreProvider.


e2e test

End-to-end testing. Test the application flow from beginning to end.

I think this suits our product, whose feature specifications are written as user stories.

Writing and running tests based on the specifications might help catch bugs before QA.

Drawbacks.

Unit and integration tests: test the developer’s intent.

E2E tests: test user behavior.

There may be some overlap with QA work.

Tests take a long time.

The test pyramid: most tests should be unit tests.

E2E testing is expensive, so it should cover only what is necessary.


If we introduce tests, we also need to discuss how to manage them.

Whether to add them to CI/CD.

Whether to run them before deployment, and so on.

What criteria should determine when to use E2E tests and unit tests?


cypress vs playwright

After trying both Cypress and Playwright:

As someone inexperienced in writing tests, I found Cypress much easier to debug because I could see the screen.

Playwright was frustrating because when I got stuck, I couldn’t tell where. I couldn’t tell whether things were working either.

Playwright: parallel testing, fast execution, and support for testing multiple browsers.

Cypress: good documentation and easy debugging.

action

locator.fill() : Fill in a form

playwright code

import { expect, Page, test } from "@playwright/test";

// describe groups tests together.
test.describe("Hyperconnect tech blog tests", () => {
	let page: Page;

	// beforeAll runs only once at the start, for initialization and similar work.
	test.beforeAll(async ({ browser, contextOptions }) => {
		const browserContext = await browser.newContext(contextOptions);
		// Create a page.
		page = await browserContext.newPage();

		// Navigate to the tech blog.
		await page.goto("https://hyperconnect.github.io/");
	});

	test("1. The document title is correct", async () => {
		// Check that document.title is correct.
		await expect(page).toHaveTitle(
			"Hyperconnect Tech Blog | 하이퍼커넥트의 기술블로그입니다."
		);
	});

	test("2. The footer copyright is correct", async () => {
		// Get the footer element.
		const copyrightFooter = await page.locator("body > footer > div > div");

		// Calculate the correct copyright.
		const currentYear = new Date().getFullYear();
		const validCopyright = `© 2013-${currentYear} Hyperconnect Inc.`;

		// Check that the footer text is the correct copyright.
		await expect(copyrightFooter).toHaveText(validCopyright);
	});

	test("3. Clicking the Careers button opens the Career page", async () => {
		// Click the Careers button.
		await page.click("body > header > div > nav > div > a:nth-child(3)");

		// Check that the careers page has opened.
		await expect(page).toHaveURL("https://career.hyperconnect.com/");

		console.log("Please check out our job openings 🙏");
		console.log("The Epic CPaaS Web team is hiring too 🙌");
		console.log("Find openings here: https://career.hyperconnect.com/");
	});

	// A deliberately failing case.
	test("4. Clicking the background 100 times switches to dark theme", async () => {
		// Go back to the tech blog.
		await page.goBack();

		// Click the background 100 times.
		for (let i = 0; i < 100; i++) {
			await page.click("body");
		}

		const body = page.locator("body");

		// Check that the background is black (dark theme).
		await expect(body).toHaveCSS("background-color", "black");
	});
});

Initial setup

Running E2E tests with Cypress

Cypress Testing Library | Testing Library

Setting up Cypress (React, TypeScript)

Type error resolved!!

cannot find name ‘cy’.ts(2304) 🔎 You.com Search

Code

// Can we test API calls too??
it('cy.request() - make an XHR request', () => {
  // https://on.cypress.io/request
  cy.request('https://jsonplaceholder.cypress.io/comments')
   .should((response) => {
    expect(response.status).to.eq(200)
    expect(response.body).to.have.length(500)
    expect(response).to.have.property('headers')
    expect(response).to.have.property('duration')
   })
 })

it('displays mobile menu on click', () => {
      cy.get('nav .desktop-menu').should('not.be.visible')
      cy.get('nav .mobile-menu')
        .should('be.visible')
        .find('i.hamburger')
        .click()

      cy.get('ul.slideout-menu').should('be.visible')

//dynamic viewport test
const sizes = ['iphone-6', 'ipad-2', [1024, 768]]

describe('Logo', () => {
  sizes.forEach((size) => {
    // make assertions on the logo using
    // an array of different viewports
    it(`Should display logo on ${size} screen`, () => {
      if (Cypress._.isArray(size)) {
        cy.viewport(size[0], size[1])
      } else {
        cy.viewport(size)
      }

      cy.visit('https://example.cypress.io')
      cy.get('#logo').should('be.visible')
    })
  })
})

Testing an API with Cypress

The other modals in Studio are not user-based. ⇒ Should these be user-based too?? ??

yarn run cypress open

Snapshot tests in Cypress

it("List page snapshot test", () => {
	cy.visit("/list"); // Navigate to the list page.

	// Capture a snapshot of the elements other than the thumbnail.
	cy.get(".list-item").each((item) => {
		cy.wrap(item).within(() => {
			// Capture a snapshot of the elements other than the thumbnail.
			cy.get(".list-item-title").snapshot({ ignore: [".thumbnail"] });
		});
	});
});

productdetailviewmodel: gets stuck at useEffect

import { ProductDetailViewModel } from "../../modules/products/viewModels/ProductDetailViewModel";
import { mockRouter } from "../../lib/pagination/test-utils";

describe("ProductDetailViewModel", () => {
	let viewModel;
	const mockProduct = { id: "1", title: "Test Product", price: 10 };
	const mockProductStore = {
		products: {
			product: mockProduct,
		},
	};
	beforeEach(() => {
		// Create and pass the required mock objects.
		const authStore = jest.fn();
		const product = mockProduct;
		const productStore = mockProductStore;
		const router = mockRouter;
		const apiService = jest.fn();

		viewModel = ProductDetailViewModel({
			authStore,
			product,
			productStore,
			router,
			apiService,
		});
	});

	test("initialize", async () => {
		console.log("This is a test, test, test");
		// Call the initialize action.
		await viewModel.actions.initialize({ prodId: "123" });

		// Write assertions for the expected behavior.
		expect(viewModel.status.initialized).toBe(true);
		expect(viewModel.status.loading).toBe(false);
		// ...
	});

	test("fetchProduct", async () => {
		// Call the fetchProduct action.
		await viewModel.actions.fetchProduct("123");

		// Write assertions for the expected behavior.
		expect(viewModel.status.errors.length).toBe(0);
		expect(viewModel.actions.currentSelectedVariant).not.toBeNull();
		// ...
	});

	// Write other test cases...
});

Cypress and Jest

If you need to choose one of these tools to improve product stability, Cypress may generally be the better fit.

Cypress specializes in end-to-end (E2E) testing, allowing you to test an application from a real user’s perspective. It can simulate and test actual application behavior, covering a wide range of scenarios such as UI interactions, navigation, API calls, and form submissions.

Because Cypress runs and controls the application in a browser, tests can run in an environment close to actual use. This helps uncover and resolve issues affecting the user experience and real behavior. It also provides powerful debugging tools and a user-friendly interface, helping developers write and debug tests efficiently.

Jest, on the other hand, is a framework mainly used for unit and module tests. It lets you test code logic and verify expected behavior. It is fast and lightweight, with powerful unit testing features, but may be less suited than Cypress to testing the actual user experience.

For product stability, then, it is a good idea to run end-to-end (E2E) tests with Cypress. You can test scenarios real users encounter and check the reliability of the application’s behavior and user interface.

[Cypress] Introducing Cypress (with MSW)

Frontend testing tips

yarn playwright test

Organize the post about test code.

Today’s lesson: when changing existing code, consider side effects and check where else it is imported.

Notes

What I learned from struggling with Jest.

Testing only the view: I need dummy versions of the actions and commands in the view model.

Testing the view model: I need dummy versions of its imports.

It never fully runs.

It is difficult to fully test the login logic.

Frontend testing approaches

  • Jest: check function behavior, as in priceOptionsfactory.spec.ts

  • Snapshot tests: UI tests (it might be useful to take screenshots of every page and run snapshot tests. → I think this would be good for spotting errors after changing styles.)

  • Cypress: user flow tests based on the product policy documents

  • Start writing tests for features added from now on.

  • Start by writing tests alongside feature development.

  • Do not add them to CI/CD for now: they take a long time, so run them manually before deployment until the process is established.

  • How can I write useful tests that actually catch bugs? ?-?


Why introduce Cypress: the limitations of Jest

Trying tests with Jest made me wonder where to draw the test boundaries. Mock functions are essential, which seems to make it difficult to test how features actually behave. Creating an environment where a view model works in Jest is particularly hard.

E2E tests seem useful for testing UI and frontend functionality together.


e2e test

End-to-end testing. Test the application flow from beginning to end.

I think this suits our product, whose feature specifications are written as user stories.

Writing and running tests based on the specifications might help catch bugs before QA.

Drawbacks.

Unit and integration tests: test the developer’s intent.

E2E tests: test user behavior.

There may be some overlap with QA work.

Tests take a long time.

The test pyramid: most tests should be unit tests.

E2E testing is expensive, so it should cover only what is necessary.


If we introduce tests, we also need to discuss how to manage them.

Whether to add them to CI/CD.

Whether to run them before deployment, and so on.

What criteria should determine when to use E2E tests and unit tests?


cypress vs playwright

After trying both Cypress and Playwright:

As someone inexperienced in writing tests, I found Cypress much easier to debug because I could see the screen.

Playwright was frustrating because when I got stuck, I couldn’t tell where. I couldn’t tell whether things were working either.

Playwright: parallel testing, fast execution, and support for testing multiple browsers.

Cypress: good documentation and easy debugging.

action

locator.fill() : Fill in a form

playwright code

import { expect, Page, test } from "@playwright/test";

// describe groups tests together.
test.describe("Hyperconnect tech blog tests", () => {
	let page: Page;

	// beforeAll runs only once at the start, for initialization and similar work.
	test.beforeAll(async ({ browser, contextOptions }) => {
		const browserContext = await browser.newContext(contextOptions);
		// Create a page.
		page = await browserContext.newPage();

		// Navigate to the tech blog.
		await page.goto("https://hyperconnect.github.io/");
	});

	test("1. The document title is correct", async () => {
		// Check that document.title is correct.
		await expect(page).toHaveTitle(
			"Hyperconnect Tech Blog | 하이퍼커넥트의 기술블로그입니다."
		);
	});

	test("2. The footer copyright is correct", async () => {
		// Get the footer element.
		const copyrightFooter = await page.locator("body > footer > div > div");

		// Calculate the correct copyright.
		const currentYear = new Date().getFullYear();
		const validCopyright = `© 2013-${currentYear} Hyperconnect Inc.`;

		// Check that the footer text is the correct copyright.
		await expect(copyrightFooter).toHaveText(validCopyright);
	});

	test("3. Clicking the Careers button opens the Career page", async () => {
		// Click the Careers button.
		await page.click("body > header > div > nav > div > a:nth-child(3)");

		// Check that the careers page has opened.
		await expect(page).toHaveURL("https://career.hyperconnect.com/");

		console.log("Please check out our job openings 🙏");
		console.log("The Epic CPaaS Web team is hiring too 🙌");
		console.log("Find openings here: https://career.hyperconnect.com/");
	});

	// A deliberately failing case.
	test("4. Clicking the background 100 times switches to dark theme", async () => {
		// Go back to the tech blog.
		await page.goBack();

		// Click the background 100 times.
		for (let i = 0; i < 100; i++) {
			await page.click("body");
		}

		const body = page.locator("body");

		// Check that the background is black (dark theme).
		await expect(body).toHaveCSS("background-color", "black");
	});
});

Initial setup

Running E2E tests with Cypress

Cypress Testing Library | Testing Library

Setting up Cypress (React, TypeScript)

Type error resolved!!

cannot find name ‘cy’.ts(2304) 🔎 You.com Search

Code

// Can we test API calls too??
it('cy.request() - make an XHR request', () => {
  // https://on.cypress.io/request
  cy.request('https://jsonplaceholder.cypress.io/comments')
   .should((response) => {
    expect(response.status).to.eq(200)
    expect(response.body).to.have.length(500)
    expect(response).to.have.property('headers')
    expect(response).to.have.property('duration')
   })
 })

it('displays mobile menu on click', () => {
      cy.get('nav .desktop-menu').should('not.be.visible')
      cy.get('nav .mobile-menu')
        .should('be.visible')
        .find('i.hamburger')
        .click()

      cy.get('ul.slideout-menu').should('be.visible')

//dynamic viewport test
const sizes = ['iphone-6', 'ipad-2', [1024, 768]]

describe('Logo', () => {
  sizes.forEach((size) => {
    // make assertions on the logo using
    // an array of different viewports
    it(`Should display logo on ${size} screen`, () => {
      if (Cypress._.isArray(size)) {
        cy.viewport(size[0], size[1])
      } else {
        cy.viewport(size)
      }

      cy.visit('https://example.cypress.io')
      cy.get('#logo').should('be.visible')
    })
  })
})

Testing an API with Cypress

Today’s tasks

Add to cart button

Clean up the code