首页 > 解决方案 > 模拟默认导出失败,但命名导出没有

问题描述

我有一个可以说 file.js 有这样的代码

const myFunc = () => {
    return {
        func1: () => {},
        func2: () => {}
    }
}

export const myObject = {
 key: ''
};

export default myFunc();

我试图在我的测试中使用 jest 来模拟这个导出。可以说 file.test.js 是测试文件。

jest.mock('./path/file', () => {
    return {
         default: {
              func1: jest.fn(),
              func2: jest.fn()
         },
         myObject: {}
    };
});

但是当我的测试运行时,它会抛出错误说_File.default.func1 is not a function

如何正确模拟具有默认导出和命名导出的 js 文件?

标签: javascriptecmascript-6jestjsmocking

解决方案


解决方案:

index.ts

const myFunc = () => {
  return {
    func1: () => {},
    func2: () => {},
  };
};

export const myObject = {
  key: '',
};

export default myFunc();

index.test.ts

import fns, { myObject } from './';

jest.mock('./', () => {
  return {
    myObject: { key: 'teresa teng' },
    func1: jest.fn(),
    func2: jest.fn(),
  };
});

describe('64003254', () => {
  it('should pass', () => {
    expect(jest.isMockFunction(fns.func1)).toBeTruthy();
    expect(jest.isMockFunction(fns.func2)).toBeTruthy();
    expect(myObject.key).toBe('teresa teng');
  });
});

单元测试结果:

 PASS  src/stackoverflow/64003254/index.test.ts (11.809s)
  64003254
    ✓ should pass (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.572s

推荐阅读