【问题标题】:Mocking default export is failing but named export not模拟默认导出失败,但命名导出没有
【发布时间】:2021-01-08 04:43:23
【问题描述】:

我可以说 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 文件同时具有默认和命名导出?

【问题讨论】:

  • func1: jest.fn() 创建一个名为 func1 的属性,其调用结果 jets.fn() ... - 因为您在该代码中调用该函数... 除非调用 jest.fn() 返回一个函数,删除 () - 或者 func1: () => { return jest.fn();} - 现在看起来就像 file.js 中的代码
  • @JaromandaX 确实有效,谢谢。但是我使用 jest.fn() 作为间谍功能传递的所有其他地方。为什么它不在那里破裂?
  • 我看不到你使用它的所有其他地方,所以我无法帮助你理解你自己的代码......如果你想调用一个函数,你可以fn() - 如果你想将函数传递给某物,您使用fn
  • 这是有道理的。谢谢你拯救了我的一天。
  • @JaromandaX jest.fn() does return a function,所以这应该可以正常工作。

标签: javascript ecmascript-6 jestjs mocking


【解决方案1】:

解决方案:

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

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 2019-09-07
    • 2018-07-25
    • 2022-07-10
    • 2021-05-09
    • 2022-01-18
    • 2022-06-25
    • 2016-08-02
    • 2018-07-27
    相关资源
    最近更新 更多