开玩笑模拟一个名为导入对象的es6

时间:2019-06-21 16:10:15

标签: typescript ecmascript-6 mocking jestjs

我想知道如何模拟导入的对象,以便用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
  });
});

谢谢!

1 个答案:

答案 0 :(得分:2)

更新后的答案

在这种情况下,您必须使用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