【问题标题】:How can I mock a function which is in other file and that return a promise?如何模拟其他文件中并返回承诺的函数?
【发布时间】:2022-02-11 01:48:01
【问题描述】:

我正在编写一个 Jest 测试。我需要测试一个调用另一个 .js 文件中的函数的函数。这个被调用的函数返回一个解析为字符串的承诺。当我开始测试时,我收到错误“file.function is not a function”,其中不是“file”,而是导入的 js 文件的名称,而不是“function”,而是返回的函数的名称承诺。

在我的测试之下:

test('test', () => {

     jest.mock('../file', () => {
         function: jest.fn().mockReturnValue('Returned String')
     });

     myFunction();
     expect().toBe();

});

解释:首先我模拟了包含返回承诺的函数的模块。使用第二个参数(jest.mock)我模拟了模拟模块中包含的函数。接下来我调用我想要测试的函数(这个函数将调用模拟函数)。最后,我测试了预期。有人可以帮助我,拜托。不知道怎么解决,谢谢大家。

【问题讨论】:

    标签: javascript unit-testing jestjs mocking automated-tests


    【解决方案1】:

    jest.mock 应该与导入处于同一级别。如果您需要测试多个案例,只需每次模拟返回/解析的值。

    import { myFunction } from './fn';
    import { function } from '../file';
    jest.mock('../file', () => {
        function: jest.fn(),
    });
    
    describe('myFunction tests', () => {
      describe('With returned string', () => {
        beforeEach(() => {
          function.mockReturnValue('Returned String');
        });
    
        it('should do sth', () => {
          myFunction();
          // expect(...).toBe(...);
        });
      });
    
      describe('With returned number', () => {
        beforeEach(() => {
          function.mockReturnValue(7);
        });
    
        it('should do other thing', () => {
          myFunction();
          // expect(...).toBe(...);
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 2017-04-05
      相关资源
      最近更新 更多