Skip to content

Instantly share code, notes, and snippets.

@DevEarley
Last active April 1, 2022 15:24
Show Gist options
  • Save DevEarley/cc7dede190253f1e60f29886ee7da042 to your computer and use it in GitHub Desktop.
Save DevEarley/cc7dede190253f1e60f29886ee7da042 to your computer and use it in GitHub Desktop.
Notes on front end testing

Notes on Frontend Testing

Use Data Attributes Rather Than CSS Selectors.

... choose selectors less prone to change. My favorite type of selector is the data attribute. A developer is less likely to change data attributes while refactoring, making them perfect for locating elements in tests. I recommend naming them in a meaningful way to clearly convey their purpose to any developers working on the source code.

* Frontend Testing Pitfalls

Don't Use AAA, Use BDD!

AAA refers to Arrange, Act, Assert. This is a tried and true pattern for unit testing things like APIS. But does that work for something like integration testing with the DOM? Consider another approach, behavioral-driven development (BDD).

BDD uses "Given, When, Then" to pattern unit tests. Consider the following:

// Jest
describe('Context menu', () => {
    it('should open the context menu on click', () => {
        // Given
        const contextButtonSelector = 'sw-context-button';
        const contextMenuSelector = '.sw-context-menu';

        // When
        let contextMenu = wrapper.find(contextMenuSelector);
        expect(contextMenu.isVisible()).toBe(false);
        const contextButton =
             wrapper.find(contextButtonSelector);
        await contextButton.trigger('click');

        // Then
        contextMenu = wrapper.find(contextMenuSelector);
        expect(contextMenu.isVisible()).toBe(true);  
    });
});

* Source code from Frontend Testing Pitfalls

Use the "Testing Trophy"

Another example of how backend testing is very different from FE testing. Take a look at the "Testing Trophy" by Kent C Dodds. https://kentcdodds.com/blog/write-tests https://twitter.com/kentcdodds/status/960723172591992832

Do Not Strive for 100% Code Coverage

Instead of striving to get 100% CC like you would in a backend test project, on the frontend that becomes more trouble than its worth.

I've heard managers and teams mandating 100% code coverage for applications. That's a really bad idea. The problem is that you get diminishing returns on your tests as the coverage increases much beyond 70% (I made that number up... no science there).

** Write tests. Not too many. Mostly integration.

Sources

* Frontend Testing Pitfalls

** Write tests. Not too many. Mostly integration.

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