测试含内部函数的JavaScript函数时遇返回值断言错误求助
withinMiles JavaScript Function Let's break down why your test is failing and how to fix it:
The Root Problem
Your withinMiles function doesn't return a boolean value directly—it returns another function (the arrow function (customer) => calculateMiles(...) <= max). When you run expect(withinMiles(250, 500)).toBe(true), you're comparing that returned function to the boolean true, which is why you get the Expected: true, Received: [Function anonymous] error.
On top of that, there's a parameter mismatch: your withinMiles expects the first argument to be an object with a distance property (since it uses miles.distance), but you're passing a raw number (250) instead. That would cause calculateMiles to receive undefined as the second argument, leading to unexpected results even after fixing the test structure.
Corrected Test Case
Here's how to adjust your test to work properly:
test("Customer is within 500 miles", () => { // 1. Create a test customer with a distance value const testCustomer = { distance: 700 }; // 2. Get the range-checking function from withinMiles // Pass an object with distance as the first argument, not a raw number const isWithinRange = withinMiles({ distance: 250 }, 500); // 3. Call the returned function with your test customer and assert the result expect(isWithinRange(testCustomer)).toBe(true); });
How It Works
- Create a test customer: We define a
customerobject with adistanceproperty, which matches what the returned arrow function expects. - Retrieve the checker function:
withinMiles({ distance: 250 }, 500)returns the function that will evaluate whether a customer's distance falls within the allowed range. - Execute the checker and assert: We call
isWithinRange(testCustomer)to get the boolean result, then assert that it equalstrue.
Bonus: Add a Negative Test
To make your test suite more robust, you can add a case where the customer is outside the allowed range:
test("Customer is outside 500 miles", () => { const testCustomer = { distance: 800 }; const isWithinRange = withinMiles({ distance: 250 }, 500); expect(isWithinRange(testCustomer)).toBe(false); });
内容的提问来源于stack exchange,提问作者user6248190

