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

sequelize-test-helpers测试belongsTo时calledWith报AssertionError如何解决

问题原因&修复方案

你存在两处代码错误,修改后即可解决报错:

  1. 关联模型传参键名不匹配
    你的模型关联代码里取的是models.Dealer,但测试代码调用associate方法时,传入的对象键是OtherModel,导致models.Dealer取值为undefined。
  2. 断言的外键名配置错误
    你在belongsTo关联中配置的外键名是dealers_did,但测试断言里写的外键名是dealer_product_dpid,这个值其实是你hasOne关联的外键名,两者不匹配导致断言失败。
    另外你的associate方法里还用到了StoreProduct模型,也需要同步传入,否则调用hasOne时也会出现取值错误。

修复后的测试代码(关联校验部分)

describe('check associations', () => {
  const Dealer = 'Dealer'
  const StoreProduct = 'StoreProduct'
  before(() => {
    DealerProduct.associate( { Dealer, StoreProduct }  )
  })
  it('defined a belongsTo association with Dealer', () => {
    chai.expect(DealerProduct.belongsTo).to.have.been.calledWith(Dealer, {
      foreignKey: {
        type: dataTypes.UUID,
        allowNull: false,
        name: 'dealers_did'
      }
    })
  })
  // 可补充hasOne关联的校验逻辑
  it('defined a hasOne association with StoreProduct', () => {
    chai.expect(DealerProduct.hasOne).to.have.been.calledWith(StoreProduct, {
      foreignKey: {
        type: dataTypes.UUID,
        allowNull: false,
        name: 'dealer_product_dpid'
      }
    })
  })
})

修改完成后重新运行测试即可正常通过。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:18:01