curriculum/challenges/english/blocks/review-testing/6724e24864b0771a4c4c9dc9.md
Here is an example of unit tests using Jest.
First, you can create a function that is responsible for returning a newly formatted string:
export function getFormattedWord(str) {
if (!str) return '';
return str.charAt(0).toUpperCase() + str.slice(1);
}
In a separate getFormattedWord.test.js file, you can write some tests to verify that the function is working as expected. The getFormattedWord.test.js file will look like this:
import { getFormattedWord } from "./getFormattedWord.js";
import { test, expect } from "jest";
test('capitalizes the first letter of a word', () => {
expect(getFormattedWord('hello')).toBe('Hello');
});
expect Function: The expect function is used to test a value.toBe(). Jest has a variety of matchers.To use Jest, you first need to install the jest package by using npm i jest. You will also need to add a script to your package.json file like this:
"scripts": {
"test": "jest"
},
Then, you can run the command npm run test to run your tests.
Different Stages of Software Development Lifecycle:
Different Models of the Software Development Lifecycle:
should.js and expect.js.Here is an example of an assertion using Chai that checks that the return value from the addThreeAndFour function is equal to the number 7:
assert.equal(addThreeAndFour(), 7);
Here is an example of E2E tests from the freeCodeCamp codebase using Playwright. The beforeEach hook will run before each of the tests. The tests check that the donor has a supporter link in the menu bar, as well as a special stylized border around their avatar:
test.beforeEach(async ({ page }) => {
execSync("node ./tools/scripts/seed/seed-demo-user --set-true isDonating");
await page.goto("/donate");
});
...
test("The menu should have a supporters link", async ({ page }) => {
const menuButton = page.getByTestId("header-menu-button");
const menu = page.getByTestId("header-menu");
await expect(menuButton).toBeVisible();
await menuButton.click();
await expect(menu).toBeVisible();
await expect(page.getByRole("link", { name: "Supporters" })).toBeVisible();
});
test("The Avatar should have a special border for donors", async ({ page }) => {
const container = page.locator(".avatar-container");
await expect(container).toHaveClass("avatar-container gold-border");
});
Once the initial development and software testing are complete, it is important to have the application tested by testers and real users. This is where alpha and beta testing come in.
Review the Testing topics and concepts.