【问题标题】:How To 'Flush' A Jest Mock (without using await)如何“冲洗”一个笑话模拟(不使用等待)
【发布时间】:2019-09-03 09:18:45
【问题描述】:

我来自 AngularJS 世界,但现在使用 React 和 Jest(带有 Jest Mock)。

我想这样做....

test('should update internal tracking variable', async () => {
        api.post = jest.fn().mock;

        expect(obj.postCallFinished).toBe(false)
        obj.begin() //this calls api.post internally with await
        expect(obj.postCallFinished).toBe(false)

        api.post.flush()
        expect(obj.postCallFinished).toBe(true)   

})

我不想在这种情况下在 obj.begin 调用中使用 await。我需要更细粒度的控制并希望检查内部跟踪变量,以便我可以慢慢地逐步完成我的应用程序的所有回调(而不破坏函数的封装)。我需要进行基于状态的测试,重要的是我可以依次缓慢地逐步完成每个阻塞调用。

请有人帮我弄清楚我如何控制承诺并缓慢地强制解决模拟问题?

【问题讨论】:

    标签: javascript mocking jestjs


    【解决方案1】:

    听起来begin 是一个async 函数,它在一系列async 函数上调用await

    您可以监视在begin 中调用的函数,并使用mockfn.mock.results 检索每个返回的Promise。然后您可以在测试中单独awaitPromises 中的每一个来检查每个步骤的状态。

    下面是一个简单的示例,可以帮助您入门:

    class MyClass {
      constructor() {
        this.state = 0;
      }
    
      async first() {
        await Promise.resolve();  // <= do something asynchronous
        this.state = 1;
      }
    
      async second() {
        await Promise.resolve();  // <= do something asynchronous
        this.state = 2;
      }
    
      async begin() {
        await this.first();
        await this.second();
        await Promise.resolve();  // <= do something asynchronous
        this.state = 3;
      }
    }
    
    test('walk through begin', async () => {
      const firstSpy = jest.spyOn(MyClass.prototype, 'first');
      const secondSpy = jest.spyOn(MyClass.prototype, 'second');
    
      const instance = new MyClass();
      const promise = instance.begin();
      expect(instance.state).toBe(0);  // Success!
      await firstSpy.mock.results[0].value;  // <= wait for the Promise returned by first
      expect(instance.state).toBe(1);  // Success!
      await secondSpy.mock.results[0].value;  // <= wait for the Promise returned by second
      expect(instance.state).toBe(2);  // Success!
      await promise;  // <= wait for the Promise returned by begin
      expect(instance.state).toBe(3);  // Success!
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 2021-12-11
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多