- How to install Jest.
- Running tests with Jest.
- Scaffold tests using mocks.
- Test fully-featured React Components.
- React 16.0.0 [v16.0.0 to v16.4.0]
- Jest 26.6.3
- General understanding of testing and realted architecture (How, Why).
- Jest Installation, test-running and detailed API Analysis.
- Moking - How and Why and Implementation.
- Unit, Component and Snapshot testing in practice.
- Prevent regression.
- Provides objective success criteria.
- Facilitates complex modular applications.
- A suite of tests is an application which checks your application.
- Composed of assertions about how your code will execute.
- Test files are comitted to the repo with application code.
- Suite is run quickly and routinely by CI tools.
- Unit Test
- Tools: Jest / Mocha
- Component Test
- Tools: Jest / Enzyme
- Snapshot Test
- Tools: Jest
- End-to-End Test
- Tools: Protractor / Cypress
- A library installed via NPM or Yarn and run via command line.
- Similar to popular test-runner but with handy extra features.
-
Jasmine/Mocha
- Test-runner that organizes tests into "describe" and "it" blocks (or "suite" and "test").
- All assertions inside tests are verified whenever the test-runner is invoked.
- Doesn't include mocking or snapshots
-
Jest
- Bulit on top of Jasmine/Mocha.
- Adds snapshot testing, mocking and many other useful features.
- Includes superior assertion library, CLI
- Works with or without React
-
Enzyme
- Not a test runner like Jest, but provides tools to test React apps specifically.
- Expresses component output as HTML (Like React Test Renderer).
- Potentially useful but not for every project.
-
Jest vs. Mocha
-
Jest Mocha -
Runs Tests Yes Yes -
Async Yes Yes -
Spies Yes No -
Snapshot Yes No -
Mocking Yes No
-
-
Jest
- The actual test-runner library which you use to execute your tests
-
Jest CLI
- A tool that you use from the command line to provide configuration options to Jest
Step 1: Install dependencies
npm install && npm run postinstallStep 2: Install Jest CLI
npm install -g jest-cliStep 3: Run Cmd jest
folderPath> jestIf you expect below erroe message:
jest.ps1 is not digitally signed. You cannot run this script on the
current system. For more information about running scripts
and setting execution policy, see about_Execution_Policies
at https:/go.microsoft.com/fwlink/?LinkID=135170.Execute this cmd:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUserStep 4: Add Jest test script in package.json
"test": "jest"- Any files inside a folder named tests are considered tests.
- Any Files with .spec or .test in their filename are considered tests.
- IT (Test)
- Method which you pass a function to that function is executed as block of tests by the test runner
- DESCRIBE (SUITE)
- An optional method for grouping any number of IT or test statements
- Create a test folder
- Create a test file named "QuestionDetail.js"
- Create a test file named "QuestionList.spec.js"
Watch for Changes - Terminal
folderpath> jest --watch- BeforeEach runs a block of code before each test.
- Usefull for setting up databases, mock instances, etc.
- BeforeAll runs code just once, before the first test.
- Inverse version of BeforeEach and BeforeAll
- Runs a block of code after each test (or after the last test).
- useful for closing open connections, terminating sub-processes.
- Contains assertions (like a regular test).
- Does not complete instantaneously.
- Can take varying amount of time, even an unknown amount of time.
- Jest must be notified that test is complete.
- Invoke the done() callback that is passed to the test.
- Return a promise from a test.
- Pass an async function to describe.
it("async test 1", done => {
setTimeout(done,100)
});it("async test 2", () => {
return new Promise(
resolve => setTimeout(resolve, 100)
)
});it("async test 3", async () => await delay(100)
);- Why Mocking
- Reduce dependencies required by tests (Faster execution).
- Prevent side-effects during testing.
- Build custom mock to facilitate desired testing procedures.
- Convincing duplicate of an object with no internal workings.
- Can be automatically or manually created.
- Has same API as original side-effects.
- Spies and other mock features simplify testing.
- Scan the original object for methods, give the new object spy methods with same names.
- Ensure that any methods which returned a promise still return a promise in the mock.
- Create mocks for any complex values that are returned from the methods which are required for tests.
- Also known as "Spies".
- No side-effects.
- Counts function calls.
- Records arguments passed when they called.
- Can be "Loaded" with return values.
- Return value must approximate original.
- Appropriately named NPM mock are loaded automatically.
- Mocks must reside in a mocks folder next to mocked modules.
- NPM modules and local modules can both be mocked.
- JSON-based record of a component's output.
- Compared to component's actual output during testing process.
- Committed along with other modules and tests to the application repo.
- Developer A authors a new component.
- Snapshot of that component's output is generated automatically.
- Developer A commits changes, moves on.
- Developer B makes a breaking change to a dependency of the new component.
- A new snapshot is automatically generated.
- Since the snapshots don't match, the test suite will fail until updated.
- Verify output has not regressed.
- Ensure that rarely occuring corner cases produces the correct output.
- If component generates side effects, verify they occur but do not execute them.
- Verify user interactions are handled as expected.
- Components may or may not have lifecycle handlers.
- Components may or may not have internal state.
- Components may or may not generate side effects.
- Component may get state from arguments, or from external dependencies.
- No internal state
- Output is an idepotent product of the props that are provided.
- No side-effects
- Any AJAX calls, UI changes or other side effects are handled by sagas, thunks, etc., but not by components.
- No lifecycle hooks
- Fetching data is handled on the application level, not the component level.
- Components don't generate side effects.
- Component consists of logical display and container components.
- Components do not have internal state.
- Test Container and Display elements separately.
- Use unit tests to verify methods and properties passed by container are accurate.
- Use snapshot tests to verify the output of the display component, passing props in directly.
- Mock dependencies, then test them.
- Use spies to verify side-effects.
- Move logic from lifecycle to services.
- Prevent regression with snapshot.
- Inject values by writing mocks for services.
- Make stateless components, where possible.
-
Also known as an assertion or expectation.
-
Represents a claim that a value will be equal (or not) to something.
-
Throws an error (test fails) if matcher's claim is not validated.
-
HandWritten test
function test(){
const value = getValue42();
if(value !== 42){
throw new Error("/**/")
}
}-
If statement (condition).
-
Throw an error.
-
In test runner, the error result in test .failing, not in the application failing.
-
Matchers
function test2(){
const value = getValue42();
expect(value).toEqual(42);
}- Equivalent test using a mathcer.
- Matcher is equivalent to if statement above.
-
Guide URL : https://jestjs.io/docs/getting-started
-
"Not" Matcher
- Reverses an assertion.
- If assertion without not would pass, asertion with not will fail.
-
"To Be" and "To Equal" Matcher
- Verify that two values are equivalent.
- Two arrays with matching elements are equal, but not identical.
- Very general - use more specific matcher when possible.
-
"To Be Close To" Matcher
- Like toEqual for numbers, but assertion still passes if number are close but not equal.
- For assertions involving floating point numbers.
-
"To Contain" & "To Have Length"
- Array matcher which verify the contents and size of a collection.
- More succinct than combining toEqual with array operators includes, length, etc.