【问题标题】:Jest mock an es6 named imported object开玩笑模拟一个 es6 命名的导入对象
【发布时间】:2019-11-04 12:25:02
【问题描述】:

我想知道如何使用 Jest 模拟导入的对象以返回假值。

在这种情况下,我想将默认超时值 (5000) 覆盖为 1000 以使我的函数崩溃

// config.ts
export const config = {
  request: {
    timeout: 5000,
  },
};
// Test file
import * as config from './config';

describe('Requests', () => {
  beforeEach(() => {
    jest.mock('./config');
  });

  afterEach(() => {
    jest.resetAllMocks();
  });

  it('Force timeout value', () => {
    jest.mock('./config');
    config.request.timeout.mockReturnValueOnce(1000);

    expect(config.request.timeout).toEqual(1000); // FAIL: returns 5000 instead of 1000
  });
});

谢谢!

【问题讨论】:

    标签: typescript ecmascript-6 mocking jestjs


    【解决方案1】:

    更新答案

    在这种情况下,您必须使用 Require 而不是 import (ESM)。

    // config.ts
    export const config = {
      request: {
        timeout: 5000
      }
    }
    

    测试文件将如下所示:

    // Test file
    
    describe('greetings', () => {
      beforeEach(() => jest.resetModules())
    
      describe('hello', () => {
        describe('when the language is set to galician', () => {
          it('returns galician for hi', () => {
            jest.mock('./config', () => ({ request: { timeout: 1000 } }))
            const { request } = require('./config')
            expect(request.timeout).toEqual(1000)
          })
        })
    
        describe('when the language is not set to galician', () => {
          it('returns hi', () => {
            jest.mock('./config', () => ({ request: { timeout: 2000 } }))
            const { request } = require('./config')
            expect(request.timeout).toEqual(2000)
          })
        })
      })
    })
    

    参考 - https://medium.com/trabe/mocking-different-values-for-the-same-module-using-jest-a7b8d358d78b

    【讨论】:

      猜你喜欢
      • 2018-10-23
      • 1970-01-01
      • 2018-07-25
      • 2020-05-27
      • 1970-01-01
      • 2020-05-17
      • 2020-08-20
      • 2018-12-30
      • 2021-07-03
      相关资源
      最近更新 更多