简体   繁体   English

如何“刷新”笑话模拟(不使用等待)

[英]How To 'Flush' A Jest Mock (without using await)

I come from the AngularJS world but now using React and Jest (with Jest Mock). 我来自AngularJS世界,但现在使用React和Jest(与Jest Mock一起使用)。

I'd like to do this.... 我想这样做。

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)   

})

I don't want to use await in this instance on the obj.begin call. 我不想在obj.begin调用的此实例中使用await。 I need more fine grain control and want to check internal tracking variables so that I can slowly step through all the callbacks of my app (without breaking encapsulation on the functions). 我需要更精细的控制,并希望检查内部跟踪变量,以便可以缓慢地逐步执行应用程序的所有回调(而不会破坏函数的封装)。 I need to do state based testing and it's important that I can slowly step through each blocking call in turn. 我需要进行基于状态的测试,重要的是,我可以依次逐步完成每个阻塞调用。

Please can someone help me figure out how I get control over the promise and slowly resolve the mock imperatively? 请有人能帮助我弄清楚我如何控制诺言并逐步解决模拟问题吗?

It sounds like begin is an async function that calls await on a series of async functions. 听起来begin是一个async函数,它对一系列async函数调用await

You can spy on the functions called within begin and retrieve the Promise that each returns by using mockfn.mock.results . 您可以监视使用begin调用的函数,并使用mockfn.mock.results检索每个函数返回的Promise Then you can await each of those Promises individually within the test to check the state at each step. 然后,您可以在测试中分别await每个Promises ,以检查每个步骤的状态。

Here is a simple example to get you started: 这是一个入门的简单示例:

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!
})

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

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