Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active December 30, 2018 21:13
Show Gist options
  • Save ivankisyov/90d629f3f2b28acb305d5546c3f78d45 to your computer and use it in GitHub Desktop.
Save ivankisyov/90d629f3f2b28acb305d5546c3f78d45 to your computer and use it in GitHub Desktop.
Writing Tests in JS

Writing Tests in JS

Testing Async Code

In order to properly handle async code, you can use the following approaches:

  • use the done callback
  • return the promise(if any of course)
  • use async/await: make sure the callback that you're passing to the it/test function is "asynced"
    • in order to test async code which should fail, you must use try/catch or switch to the second appoach listed here and use the catch method on the promise that had been rejected;

AAA Principle:

  • Arrange
  • Action
  • Assertion
describe("The validateName function", () => {
  it("should create new error message if the user name is less than 5 characters", () => {
  
    // Arrange
    const user2 = new User("tom", "tom@test.com");
    
    // Action
    user2.validateName();

    // Assertion
    expect(user2.errors).toEqual(["the name must be at least 5 chars long"]);
  });
});

Make sure you're not writing evergreen tests

If your test is passing, make sure to temporary change something on the passing test. If the test fails now, then the test is not evergreen.

Helpful packages:

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