Skip to content

Instantly share code, notes, and snippets.

@wktdev
Created September 6, 2019 18:58
Show Gist options
  • Select an option

  • Save wktdev/2d2194123e8aa5de58317bf9f4419c7b to your computer and use it in GitHub Desktop.

Select an option

Save wktdev/2d2194123e8aa5de58317bf9f4419c7b to your computer and use it in GitHub Desktop.

Start a new node app:

npm init.

In package.json set a key/value of "private":true AND set scripts to {"test":"jest"}

{
  "name": "test-driven-fizzbuzz",
   "private":true,       // <------------here
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {                
    "test":"jest         // <----------- here
  },

  "author": "",
  "license": "ISC"
}


Testing

To begin testing you will need two packages. The first is JEST and the second is Enzyme. You will first learn unit testing with JEST.

JEST

Jest is used for unit testing.

npm test

No test will be found and the aformentioned command will return an error.

Create the following code and save it as: greeting.test.js

const greeting = guest => `Hello, ${guest}!`;


describe('greeting()', ()=>{
	it('says hello',()=>{
		expect(greeting("Jest")).toBe('Hello, Jest!');
	});
});

describe() describe() declares a test suite, which is a group of tests.Its first function is a name(the name can be anything and does not need to mirror the functions name) and the second argument is a function containing one or more test.

it() it() declares a test. The first argument it takes is its name. The second argument is a function with actual test code.

expect() expect() creates an assertion. It takes a single argument that is typically a value that is the result of the code being tested.

.toBe()

toBe() is a strict equality operator that checks the result of expect() and matches against its own argument.

.toEqual()

expect(1+2).toEqual(4)

Watch for Test Changes

npx jest --watchAll

Enzyme

Install Enzyme. Instructions here: https://github.com/airbnb/enzyme

Short version for react 16: npm i --save-dev enzyme enzyme-adapter-react-16

Example use with Jest

Clone, npm install and npm test the example. Link to example: https://github.com/vjwilson/enzyme-example-jest

More details: https://github.com/airbnb/enzyme/blob/master/docs/guides/jest.md

Testing Interactive Events

https://github.com/facebook/jest/tree/master/examples/enzyme

Testing a Response to an Async API call

https://www.asapdevelopers.com/async-code-testing-react-jest-enzyme/

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