无法访问 jest.mock 函数中的变量

IT技术 reactjs unit-testing mocking jestjs
2021-05-12 05:11:39

请检查以下场景

const url = 'https://mock.com/mockpath';
jest.mock('../../src/somefile', () => {
  return ({
    getURL: jest.fn(() => url),
  });
});

我收到错误

babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
Invalid variable access: url
2个回答

礼貌@skyboyer

刚刚将 url 重命名为 mockUrl,任何以 mock 开头的变量都可以在 jest.mock 中访问。

@skyboyer再次感谢您的帮助。

'jest.mock()' is not allowed to reference any out-of-scope variables. Invalid variable access: mockURL

它告诉您jest.mock()正在尝试访问mockURL,但不允许访问范围外变量。

您应该mockURLjest.mock()函数调用中声明

jest.mock('../../src/somefile', () => {
  const mockURL = 'https://mock.com/mockpath';
  return ({
    getURL: jest.fn(() => mockURL),
  });
});

或者你可以只引用字符串而不使用中间变量:

jest.mock('../../src/somefile', () => ({
  getURL: jest.fn(() => 'https://mock.com/mockpath'),
}));