What is Unit Testing?
Unit testing, a testing technique using which individual modules are tested to determine if there are any issues by the developer himself. It is concerned with functional correctness of the standalone modules.
The main aim is to isolate each unit of the system to identify, analyze and fix the defects.
Unit Testing - Advantages:
- Reduces Defects in the Newly developed features or reduces bugs when changing the existing functionality.
- Reduces Cost of Testing as defects are captured in very early phase.
- Improves design and allows better refactoring of code.
- Unit Tests, when integrated with build gives the quality of the build as well.
For testing our app, first of all, we need a test runner.
When we create a new react app, the create-react-app provides us a test runner which is called Jest.
At first, we have to create react app:
npx create-react-app my-app-name --template typescript
yarn create react-app my-app-name --template typescript
Now, we can get two file as naming App.tsx and App.test.tsx
In App.test.tsx we have to ensure that the App component renders a link.
test('renders learn react link', () => {
render(<App />);
Let's go understand unit testing anatomy.
Unit Testing (AAA)
We describe what we want to test.
- Arrange: prepare the testing environment, render the component;
- Act: try to find expected value;
- Assert: we compare function results with expected results, if they are equal the function worked correctly.
Unit testing sample
Say, we have a divided function, we expect the correct result and we also know that if we divided by 0, it's not valid. So, it will throw an error. If we set (10/5) and we expect the value=2, that's quite possible. But if we set (10/5) and we expect the value=3, it will throw an error. We will test our App.tsx component in our App.test.tsx
// ...
it("should return a division result", () => {
// Arrange: prepare function arguments
// and the expected division result.
// In this example 10 / 2 === 5:
const [a, b, expected] = [10, 2, 5];
// Here we use array destructuring
// to assing `a === 10`, `b === 2`,
// and `expected === 5`.
// Act: use the `divide` function
// to get an actual function result.
const result = divide(a, b);
// Assert: compare expected result
// with a function result.
expect(result).toEqual(expected);
});
In our case we use .toEqual method to check if the expect argument is equal to toEqual argument, i.e. if the expected result is equal to actual result.
Now, it is time to check if our test is working, open the console and run:
yarn test
You will see that all the tests are passing:
Top comments (2)
following this setup results in
SyntaxError: Cannot use import statement outside a module
for meYou can explore the solution by searching on google. Here is the link, it may be help you..
stackoverflow.com/questions/582118...