如何克服开玩笑“初始化前无法访问"问题? [英] How to overcome jest "Cannot access before initialization" problem?

查看:173
本文介绍了如何克服开玩笑“初始化前无法访问"问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

settings.js

export default {
  web: {
    a: 1
  },
  mobile: {
    b: 2
  }
};

getSetting.js

import settings from "./settings";

export const getSetting = platform => {
  return settings[platform];
};

getSettings.test.js

import { getSetting } from "./getSetting";

const TEST_SETTINGS = { c: 3 };

jest.mock("./settings", () => {
  return {
    test: TEST_SETTINGS
  };
});

test("getSetting", () => {
  expect(getSetting("test")).toEqual(TEST_SETTINGS);
});

错误

ReferenceError: Cannot access 'TEST_SETTINGS' before initialization

我相信这与起吊有关.有没有办法解决这个问题?开玩笑是否提供其他手段来实现这一目标?

I believe this has something to do with hoisting. Is there a way to overcome this issue? Does jest provide any other means to achieve this?

我不想这样做.当模拟数据很大并且在多个测试中使用时,这不是很好.

I don't want to do this. This is not good when the mock data is large and used in multiple tests.

jest.mock("./settings", () => {
  return {
    test: { c: 3 }
  };
});

expect(getSetting("test")).toEqual({ c: 3 });

推荐答案

jest.mock

jest.mock is automatically hoisted, this results in evaluating mocked module before TEST_SETTINGS is declared.

此外,这还会导致./settings被名为test模拟,而预期具有默认的导出功能.

Also, this results in ./settings being mocked with test named export, while it's expected to have default export.

它不应使用临时变量,该值在导入时可用:

It shouldn't use temporary variable, the value is available when it's being imported:

import settings from "./settings";

jest.mock("./settings", () => {
  return { default: {
    test: { c: 3 }
  } };
});

...

expect(getSetting("test")).toBe(settings.test);

这篇关于如何克服开玩笑“初始化前无法访问"问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆