You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

测试含内部函数的JavaScript函数时遇返回值断言错误求助

Fixing the Test Case for 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

  1. Create a test customer: We define a customer object with a distance property, which matches what the returned arrow function expects.
  2. Retrieve the checker function: withinMiles({ distance: 250 }, 500) returns the function that will evaluate whether a customer's distance falls within the allowed range.
  3. Execute the checker and assert: We call isWithinRange(testCustomer) to get the boolean result, then assert that it equals true.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:57:47