All quizzesEasy
Unit Testing — Series 2
Preview — 3 of 10 questions
Which best describes the Arrange-Act-Assert (AAA) structure commonly recommended for writing unit tests?
javascript
test('cart total includes tax', () => {
// Arrange
const cart = new ShoppingCart();
cart.addItem({ price: 100 });
// Act
const total = cart.getTotalWithTax(0.1);
// Assert
expect(total).toBe(110);
});AArrange sets up the test's initial data/objects; Act performs the action being tested; Assert verifies the expected outcome — structuring tests this way keeps them consistently readable.
BAAA means every test must contain exactly three expect() calls.
CArrange configures the test framework; Act runs all tests; Assert generates the coverage report.
DArrange, Act, and Assert are three separate test files that must be run in that order.
What happens when this test runs?
javascript
test('object comparison', () => {
const user1 = { name: 'Alice' };
const user2 = { name: 'Alice' };
expect(user1).toEqual(user2);
expect(user1).toBe(user2);
});ABoth assertions pass, since user1 and user2 have identical contents.
BThe first assertion (toEqual) passes because it checks structural/deep equality; the second assertion (toBe) fails because it checks strict reference equality, and user1/user2 are two distinct objects in memory.
CBoth assertions fail, since toEqual and toBe both require reference equality.
DThe first assertion (toEqual) fails; the second (toBe) passes.
Why does the second test pass, given that the first test already incremented counter.value to 1?
javascript
let counter;
beforeEach(() => {
counter = { value: 0 };
});
test('increments from 0', () => {
counter.value += 1;
expect(counter.value).toBe(1);
});
test('starts fresh in each test', () => {
expect(counter.value).toBe(0);
});AbeforeEach re-runs its setup code before every individual test, giving each test a brand-new counter object — so the second test never sees the mutation made by the first test.
BBoth tests share the exact same counter object, and JavaScript automatically resets object properties between test() blocks.
CThe second test fails, since counter.value is still 1 from the previous test.
DbeforeEach only runs once, before the very first test in the file.
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.