【问题标题】:Jest Custom Matchers: "this" is undefined inside matcher开玩笑自定义匹配器:“this”在匹配器中未定义
【发布时间】:2020-07-07 00:14:30
【问题描述】:

根据文档https://jestjs.io/docs/en/expect#custom-matchers-api 我创建了我的匹配器,但是this === undefined 在匹配器函数中。 我想使用文档中描述的帮助器,例如this.isNot,但它们不可用。

这种行为的原因可能是什么?

setupJestExpect.ts:

expect.extend({
  toBeMoment(received: any): CustomMatcherResult {

    console.log(this); // undefined <-- here

    const pass: boolean = moment.isMoment(received) as boolean;
    return pass
      ? { pass, message: () => '' }
      : { pass, message: () => 'expected that received value to be an instance of Moment' };
  }
});

foo.spec.ts:

describe('Foo', () => {
  it('should do something', async (): Promise<void> => {
    // const data: any[] = ....
    expect(data).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          bar: expect.toBeMoment()
        })
      ])
    );
  });
});

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    由于您调用它的方式,匹配器正在执行上下文中获取undefined

    如果你调用它:

    const m = moment();
    expect(m).toBeMoment();
    

    您在this 中收到预期值。

    【讨论】:

      猜你喜欢
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多