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

如何使用Sinon Spy监听返回Axios响应的异步函数并获取返回值

问题原因

  • helper.postAlbum是async异步函数,它的返回值本质是Promise对象,spy.returnValues存储的是函数同步返回的原始值,也就是未完成状态的Promise,你直接访问这个Promise的date属性自然会得到undefined。
  • 你的测试代码没有正确处理异步流程,断言执行时postAlbum的异步请求还没有完成,也没有等待Promise resolve就直接访问返回值。

解决方案

  1. 首先修正测试的异步处理逻辑,推荐直接用chai-http的Promise调用方式,避免回调嵌套导致的异步时序问题。
  2. 拿到spy记录的Promise后,用await等待它完成,再访问返回值的属性,或者直接使用sinon提供的resolvedValues属性获取异步函数resolve后的结果。

修正后的测试代码示例:

const sinon = require('sinon');
const helper = require('./helper');
const { expect } = require('chai');

describe('album create', () => {
  // 每个测试用例前后重置spy,避免数据污染
  beforeEach(() => sinon.spy(helper, 'postAlbum'));
  afterEach(() => helper.postAlbum.restore());

  it('should return valid date when postAlbum is called', async () => {
    // 等待接口请求完成
    await chai.request(app)
      .post('/create')
      .send({ /* 传入你需要的测试参数 */ });

    // 验证调用次数
    expect(helper.postAlbum).to.have.been.calledOnce;
    // 方法1:等待spy返回的Promise完成后验证
    const postRes = await helper.postAlbum.returnValues[0];
    expect(postRes).to.have.property('date').and.not.null;
    // 方法2:直接使用sinon的resolvedValues获取异步返回结果(sinon v9+支持)
    // expect(helper.postAlbum.resolvedValues[0]).to.have.property('date').and.not.null;
  });
});

额外注意

你现有代码还存在一些语法和拼写错误,建议一并修正避免其他异常:

  • album.js中createAlbum的函数语法错误,应改为async function createAlbum(pictures) {,pic.map的写法应改为pictures.map(pic => {
  • 代码中多处存在拼写错误:参数名catergory和实际使用的category不一致,会导致传参异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:57:01