遇到在导入文件并在jest.mock内使用时出现的问题。

huangapple go评论92阅读模式
英文:

Facing issue when import file and use inside jest.mock

问题

我正在尝试从另一个文件中导出对象,并在jest.mock内部使用它。

  1. jest.mock('@theme/theme-provider', async () => {
  2. const dummyThemeStyle = await import(
  3. 'app/style/__tests__/themeObjct.json'
  4. );
  5. return {
  6. useTheme: () => ({
  7. themeStyle: {
  8. ...dummyThemeStyle,
  9. },
  10. }),
  11. };
  12. });

但它始终返回useTheme不是一个函数。如何解决这个问题?

英文:

I am trying to export the object from another file and use it inside the jest.mock.

  1. jest.mock('@theme/theme-provider', async() => {
  2. const dummyThemeStyle = await import(
  3. 'app/style/__tests__/themeObjct.json'
  4. );
  5. return {
  6. useTheme: () => ({
  7. themeStyle: {
  8. ...dummyThemeStyle,
  9. },
  10. }),
  11. };
  12. });

but it always return useTheme is not a function How to solve this issue

答案1

得分: 1

移除 async/await 并在 factory 函数内部使用 require 加载模块。工厂函数如何被调用?请参阅 v29.5.0/packages/jest-runtime/src/index.ts#L1000

  1. if (this._mockFactories.has(moduleID)) {
  2. // 以上的检查使这个操作合法
  3. const module = this._mockFactories.get(moduleID)!();
  4. mockRegistry.set(moduleID, module);
  5. return module as T;
  6. }

如您所见,工厂函数不应是异步函数

  1. jest.mock('@theme/theme-provider', () => {
  2. const dummyThemeStyle = require('app/style/__tests__/themeObjct.json');
  3. return {
  4. useTheme: () => ({
  5. themeStyle: {
  6. ...dummyThemeStyle,
  7. },
  8. }),
  9. };
  10. });
英文:

Remove async/await for the factory function and use require to load the module inside the factory function. How the factory function be called? see v29.5.0/packages/jest-runtime/src/index.ts#L1000

  1. if (this._mockFactories.has(moduleID)) {
  2. // has check above makes this ok
  3. const module = this._mockFactories.get(moduleID)!();
  4. mockRegistry.set(moduleID, module);
  5. return module as T;
  6. }

As you can see, the factory function should not be an asynchronous function

  1. jest.mock('@theme/theme-provider', () => {
  2. const dummyThemeStyle = require('app/style/__tests__/themeObjct.json');
  3. return {
  4. useTheme: () => ({
  5. themeStyle: {
  6. ...dummyThemeStyle,
  7. },
  8. }),
  9. };
  10. });

huangapple
  • 本文由 发表于 2023年6月22日 19:24:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定