【问题标题】:Mock an import from another file but still return a mock value模拟从另一个文件导入,但仍返回模拟值
【发布时间】:2020-02-13 10:14:03
【问题描述】:

我正在测试一个调用从anotherFile 导入的另一个函数的函数。 outsideFunc 返回一个包含“名称”的对象。我需要它存在以便通过我的其余测试/功能正常工作。

systemUnderTest.js

import { outsideFunc } from './anotherFile.js';

function myFunc() {
   const name = outsideFunc().name;
}

另一个文件.js:

export function outsideFunc() {
   return { name : bob }
}

我不关心测试anotherFileoutsideFunc 的结果,但我仍然需要返回一个模拟值作为测试myFunc 的一部分;

systemUnderTest.spec.js

describe("A situation", () => {
  jest.mock("./anotherFile", () => ({
    outsideFunc: jest.fn().mockReturnValue({
      name: 'alice'
    })
  }));

  it("Should continue through the function steps with no problems", () => {
    expect(excludeCurrentProduct(initialState)).toBe('whatever Im testing');
  });
});

我遇到的问题是,当单元测试通过myFunc 工作时,const name 返回undefined,它应该返回alice。我希望它能够从我的anotherFile 文件的jest.mock 及其模拟导出函数中获取数据,但它没有得到正确的响应。

当我拥有我期望的name = alice 时,我实际上得到了name = undefined

【问题讨论】:

    标签: javascript unit-testing ecmascript-6 jestjs


    【解决方案1】:

    systemUnderTest.js

    import { outsideFunc } from './anotherFile.js';
    
    // let's say that the function is exported
    export function myFunc() {
       const name = outsideFunc().name;
       // and let's say that the function returns the name
       return name;
    }
    

    你可以在你的描述

    systemUnderTest.spec.js

    import { myFunc } from './systemUnderTest';
    import { outsideFunc } from './anotherFile';
    
    // using auto-mocking has multiple advantages
    // for example if the outsideFunc is deleted the test will fail
    jest.mock('./anotherFile');
    
    
    describe('myFunc', () => {
      describe('if outsideFunc returns lemons', () => {
        outsideFunc.mockReturnValue({name: 'lemons'});
        it('should return lemons as well', () => {
          expect(myFunc()).toEqual('lemons');
        });
      });
    });
    

    working example

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 2019-09-19
      • 2015-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多