繁体   English   中英

使用TypeScript和Chai进行强类型的深度相等声明

[英]Strongly typed deep equal assertion with TypeScript and Chai

我有一个TypeScript函数,返回一个Foo类型:

interface Foo {
  bar: string;
  baz: string;
}

function getFoo(): Foo {
  return {
    bar: 'hello',
    baz: 'world',
  };
}

// Chai Assertion
it('Should return a Foo', () => {
  expect(getFoo()).to.deep.equal({
    bar: 'hello',
    baz: 'world',
  });
})

当我更改Foo接口时,我的getFoo()函数会产生TypeScript错误:

interface Foo {
  bar: number;  // change these to numbers instead
  baz: number;
}

function getFoo(): Foo {
  // Compile time error! Numbers aren't strings!
  return {
    bar: 'hello',
    baz: 'world',
  };
}

但是,我的Mocha测试不会触发编译时错误!

有一种类型安全的方式来做expect().to.deep.equal()吗? 就像是:

// Strawman for how I'd like to do type-safety for deep equality assertions,
// though this generic signature still seems unnecessary?
expect<Foo>(getFoo()).to.deep.equal({
  bar: 'hello',
  baz: 'world',
});

有一种类型安全的方式来做Expect()。to.deep.equal()

不在的类型定义equal其是有意any因为它被设计用于运行时检查。

但是容易在外部执行:

const expected: Foo = {
  bar: 'hello',
  baz: 'world',
};
expect(getFoo()).to.deep.equal(expected);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM