简体   繁体   English

用笑话进行JavaScript单元测试:如何模拟异步调用

[英]javascript unit testing with jest: how to mock async call

I am new to TypeScript, earlier worked on Java. 我是TypeScript的新手,之前在Java上工作过。 I am looking for java junit(Mockito) equivalent to TypeScript. 我正在寻找与TypeScript等效的java junit(Mockito)。 In junit in each test we can define the dependency behavior and return the response as per the test case demand. 在每个测试的junit中,我们可以定义依赖行为并根据测试用例需求返回响应。 is there similar way available in jest also ? 笑话中也有类似的方法吗? in which i can simply define. 我可以在其中简单定义。 when(dependencyFunction()).then(mockResponse1); 当(dependencyFunction()),然后(mockResponse1)。

and in different test when(dependencyFunction()).then(mockResponse2); 在不同的测试中when(dependencyFunction())。then(mockResponse2);

Here is how my typescript class look like: 这是我的打字稿类的样子:

class ABC {
   static fun1(){
       const xyz = await dependency();
       return xyz === 'DONE';
   }
}

Here i want to write test cases in which i can define the mocked response in each test cases. 在这里,我想编写测试用例,在其中可以定义每个测试用例中的模拟响应。

from the documentation you can use mock functions for this and use mockReturnValueOnce or mockReturnValue for your responses 文档中,您可以为此使用模拟函数,并为您的响应使用嘲笑返回值mockReturnValueOncemockReturnValue

const myMock = jest.fn();

myMock
  .mockReturnValueOnce(10) // set the response once
  .mockReturnValueOnce('x')
  .mockReturnValue(true); // set a persistent response 

console.log(myMock(), myMock(), myMock(), myMock());
// > 10, 'x', true, true

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

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