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

如何使用Jasmine校验API测试用例响应?及场景测试写法

Jasmine + Sinon 测试API核心方法响应匹配指南

Hey there! Looks like you're working on writing Jasmine tests for your API's core() method using Sinon, and you want to verify that the returned response matches your predefined success result. Let me walk you through exactly how to do this, plus fill out that partial test code you shared.

Core Approach: Mock HTTP Requests + Assert Return Values

Since your core() method calls out to an HTTP endpoint via HttpRequest, the first step is to mock that HTTP call with Sinon so it returns your predefined success object directly. Then you can call core() and assert that its return value matches your expected result perfectly.

Complete Test Code Implementation

Here's the full, working version of your test file with explanations in comments:

import { GetAccountBalance } from './GetAccountBalance.node'
import { Promise } from 'es6-promise'
import { HttpRequest } from '../../../core/http/HttpRequest.node'
import * as sinon from 'sinon'
import { getValidationError } from '../../../common/ValidationErrorFactory'

// Use Sinon sandbox for easy cleanup of all mocks after tests
const sandbox = sinon.createSandbox()

// Restore sandbox to clean up all mocks once all tests finish
afterAll(function afterTests () {
  sandbox.restore()
})

describe('getAccountBalance', function () {
  // Instantiate the module we're testing
  const module = new GetAccountBalance()
  const testURL = 'https://essdd.max.com:4535'
  const urlPath = '/webServices/instrument/accountBalance'
  const fullURL = testURL + urlPath
  const options = { isJSON: true }
  
  // Predefined successful response we expect to get back
  const expectedSuccessResponse = {
    header: {
      serviceName: 'accountBalance',
      statusCode: '0000',
      statusDesc: 'SUCCESS',
    },
    response: {
      balanceAccount: '6346.44',
    },
  }
  
  // Valid parameters to pass to core()
  const validParams = {
    Id: '21544',
    appName: 'instrucn',
    channelName: 'Web'
  }

  describe('when core() is called with valid parameters', function () {
    let result: any
    let stubbedHttp: sinon.SinonStubbedInstance<HttpRequest>

    beforeEach(async function () {
      // 1. Create a stubbed instance of HttpRequest
      stubbedHttp = sandbox.createStubInstance(HttpRequest)
      // Make the stubbed HTTP method return our predefined success response (adjust to your actual HTTP method: get/post/etc)
      stubbedHttp.get.resolves(expectedSuccessResponse)
      
      // 2. Inject the stubbed HttpRequest into your module
      // Note: Adjust this line to match how your module receives HttpRequest (constructor injection, setter, etc)
      module.httpRequest = stubbedHttp

      // 3. Call the core() method with valid params and store the result
      result = await module.core(validParams)
    })

    it('should return the exact expected success response', function () {
      // Use Jasmine's toEqual() for deep object comparison
      expect(result).toEqual(expectedSuccessResponse)
    })

    it('should call HttpRequest with the correct URL and options', function () {
      // Verify the HTTP call was made with the right arguments
      expect(stubbedHttp.get.calledOnceWith(fullURL, options)).toBe(true)
    })

    it('should not trigger any validation errors', function () {
      // Ensure the error factory wasn't called for valid params
      const stubbedEC = sandbox.spy(getValidationError)
      expect(stubbedEC.called).toBe(false)
    })
  })
})

Key Steps Explained

  • Mock the HTTP Client: sinon.createStubInstance creates a fake version of HttpRequest, and resolves() makes its request method return your predefined success response. This avoids hitting real backend services during tests.
  • Inject the Mock: Make sure your GetAccountBalance module uses the stubbed HttpRequest instead of the real one. Adjust this part to match your module's dependency injection pattern (constructor, setter, etc).
  • Assert the Result: Use expect(result).toEqual(expectedSuccessResponse) to do a deep comparison of the returned value and your expected object—this checks every field to ensure they match exactly.
  • Extra Validations (Optional): Add tests to verify the HTTP call was made with the correct URL/options, or that validation errors aren't triggered for valid inputs. These make your tests more robust.

Bonus: Testing Failure Scenarios

If you need to test error cases (like invalid params or failed HTTP calls), here's how you might structure that:

describe('when core() is called with invalid parameters', function () {
  let result: Error
  const invalidParams = { ...validParams, Id: '' } // Invalid ID for testing

  beforeEach(async function () {
    const stubbedEC = sandbox.stub(getValidationError).returns(new Error('Invalid account ID'))
    
    try {
      await module.core(invalidParams)
    } catch (err) {
      result = err as Error
    }
  })

  it('should throw a validation error', function () {
    expect(result.message).toBe('Invalid account ID')
    expect(getValidationError.calledWith('Id')).toBe(true)
  })
})

内容的提问来源于stack exchange,提问作者hussain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:03:12