【问题标题】:Jest - mocking imported function from another file not working开玩笑 - 从另一个文件中模拟导入的函数不起作用
【发布时间】:2021-04-15 19:52:08
【问题描述】:

我一直在尝试模拟一个在另一个文件中导入并在类中使用的函数。这里有类似的问题,我经历了很多,但仍然无法让我的测试正常工作。这是我的代码结构:

//util.js
export const stageHelper = (key) => {
    return STAGE_NAMES[key];
};

//main.js
import {stageHelper} from './util'
class Main {
    static config = {
        value: stageHelper('abc'),
    }
    
    static getValue() {
        return this.config.value;
    }
}

//main.spec.js
import * as util from './util';
import {Configuration} from '../configuration/configuration';
jest.mock('./util');

describe('Main', () => {
    const utilSpy = jest.spyOn(util, 'stageHelper').mockImplementation(() => 'testValue');
    //util.stageHelper = jest.fn().mockImplementation(() => 'testValue'); // tried this too
    //utilSpy.mockReturnValue('ja'); // tried this too
    
    expect(Main.getValue()).toEqual('testValue'); // this test fails - the value is 'undefined'
});

从我的测试中调用Main.getValue() 时,我得到undefined。但是,我希望这会返回 testValue,因为这就是我模拟的返回值。

有人可以帮我解决这个问题吗?这将不胜感激!

【问题讨论】:

  • (在导入 Configuration 之前,您是否尝试过模拟 ./util?我不确定这是否重要。)
  • 是的,这就是我所做的

标签: javascript reactjs testing jestjs mocking


【解决方案1】:

您应该在导入 main.js 之前监视 util.stageHelper() 方法。您需要使用require() 方法而不是importimport 将导入 util.js 的原始版本。在你的测试用例中窥探为时已晚。

例如

util.js:

const STAGE_NAMES = {
  a: '1',
};
export const stageHelper = (key) => {
  return STAGE_NAMES[key];
};

main.js:

import { stageHelper } from './util';

export class Main {
  static config = {
    value: stageHelper('abc'),
  };

  static getValue() {
    return this.config.value;
  }
}

main.spec.js:

import * as util from './util';

describe('Main', () => {
  it('should pass', () => {
    const utilSpy = jest.spyOn(util, 'stageHelper').mockReturnValueOnce('testValue');
    const { Main } = require('./main');
    expect(utilSpy).toBeCalledWith('abc');
    expect(Main.getValue()).toEqual('testValue');
  });
});

单元测试结果:

 PASS  examples/67115206/main.spec.js (12.867 s)
  Main
    ✓ should pass (44 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |    87.5 |      100 |      50 |   85.71 |                   
 main.js  |     100 |      100 |     100 |     100 |                   
 util.js  |      75 |      100 |       0 |   66.67 | 5                 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        16.066 s

【讨论】:

  • 感谢您的回答!如果在此块之前没有测试,则此方法确实有效。但是,对于我对 Main 类的其他测试,Main.getValue() 是未定义的。我也尝试自行移动这个描述块。你知道为什么会这样吗?
猜你喜欢
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 2022-10-24
  • 2020-10-01
  • 2018-04-29
  • 2021-08-01
  • 2021-09-06
相关资源
最近更新 更多