【问题标题】:Jest mock factory functions from named exports来自命名导出的 Jest 模拟工厂函数
【发布时间】:2021-07-17 23:52:33
【问题描述】:

我想模拟这个,所以我只模拟 Bar 的 get() 返回方法,所以当 Foo 调用 find() 时, get() 被模拟并返回。

条形文件

// bar file
function Bar(){
  function get(){
    //...
  }
  return {
    get
  }
}
export default Bar;

Foo 文件

// foo file
import Bar from './bar';
function Foo(func){
  const bar = Bar();
  function find(){
    bar.get();
  }
  return {
    find,
  };
}
export default Foo

索引.js

// index.js
import Bar from './bar';
import Foo from './foo';
export {Bar, Foo};

我的测试

//foo test
import {Bar, Foo} from './index'

//This mocks everything
jest.mock('./index');

// This will say Cannot find module Bar
jest.mock('Bar', () => ({
  get: () => jest.fn().mockReturnValue('test'),
}));
    
describe('test foo', ()=> {
  let foor = Foo();
  foo.find();
})

我尝试模拟 Bar 本身,它说“找不到模块 Bar”

如何模拟 Bar 这个工厂函数?

【问题讨论】:

    标签: unit-testing jestjs


    【解决方案1】:

    假设您已将foo.jsbar.js 放入文件夹 eg:'common' 并具有如下index.js 文件,您可以这样写。 因为我们想根据您添加的代码 sn-p 模拟Bar,所以它应该返回一个function,它在调用时返回一个object,它的get 属性的值为function。确保在模拟时,因为没有任何第三方库提供我们正在模拟的文件的相对路径,在这种情况下它是 ./common/bar

      //bar.js
        function Bar(){
            function get(){}
            return {
              get
            }
          }
        
        export default Bar;
        
        //foo.js
        import Bar from './bar';
        
        function Foo(func){
          const bar = Bar();
          function find(){
            return bar.get(); //Note the return 
          }
          return {
            find,
          };
        }
        export default Foo
        
        //index.js
        import Bar from './bar';
        import Foo from './foo';
        export {Bar, Foo};
        
        //app.test.js
        import { Foo } from './common'
        
        jest.mock('./common/bar', () => (function(){
          return(
            {
              get: jest.fn().mockReturnValue('test') //Note this
            }
          )
        }));
            
        describe("Foo function", () => {
          it("Should call and return correct value", () => {
            let foor = Foo();
            expect(foor.find()).toEqual("test");
          });
        });
    

    【讨论】:

    • 谢谢,看来我返回的是对象而不是函数。干杯。
    猜你喜欢
    • 2018-06-17
    • 2022-07-09
    • 2019-02-25
    • 2017-02-06
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多