如何部分测试 json 对象的形状和部分测试值

我想在我的摩卡期望中测试我的 json 的形状。我知道一些东西,例如“名称”,但其他东西(_id)来自数据库。对于他们来说,我只关心他们设置正确的类型。


在这里我有我的期望:


expect(object).to.eql({

  recipe:

  {

    _id: '5fa5503a1fa816347f3c93fe',

    name: 'thing',

    usedIngredients: []

  }

})

如果可能的话我宁愿做这样的事情:


expect(object).to.eql({

  recipe:

  {

    _id: is.a('string'),

    name: 'thing',

    usedIngredients: []

  }

})

有谁知道有什么方法可以实现这一目标?或者最好将其分解为多个测试?


白衣染霜花
浏览 114回答 1
1回答

慕田峪4524236

您可以使用chai-json-pattern插件来做到这一点。Chai JSON 模式允许您为 JavaScript 对象创建蓝图,以确保关键信息的验证。它使您能够使用 JSON 语法扩展和易于使用的验证器。它主要用于使用 cucumber-js 测试 API,但可以在任何应用程序中使用。此外,您可以使用自定义验证器扩展基本功能例如const chai = require('chai');const chaiJsonPattern = require('chai-json-pattern').default;chai.use(chaiJsonPattern);const { expect } = chai;describe('64715893', () => {  it('should pass', () => {    const object = {      recipe: {        _id: Math.random().toString(),        name: 'thing',        usedIngredients: [Math.random() + 'whatever'],      },    };    expect(object).to.matchPattern(`{      "recipe": {        "_id": String,        "name": "thing",        "usedIngredients": Array,      },    }`);  });});测试结果:  64715893    ✓ should pass  1 passing (50ms)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript