簡體   English   中英

開玩笑 - mocking 從另一個文件導入 function 不起作用

[英]Jest - mocking imported function from another file not working

我一直在嘗試模擬在另一個文件中導入並在 class 中使用的 function。 這里有類似的問題,我經歷了很多,但仍然未能讓我的測試正常工作。 這是我的代碼的結構:

//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 ,因為這是我嘲笑返回值的原因。

有人可以幫我解決這個問題嗎? 這將不勝感激!

您應該在 import main.js 之前監視main.js util.stageHelper()方法。 您需要使用require()方法而不是import import將導入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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM