javascript - 如何更改 Jest 中模拟模块中函数的模拟实现

标签 javascript jestjs mocking

我有一个看起来像这样的 utils 文件

// utils.js
const getNextDate = (startDate) => moment(startDate, 'MMM Do YYYY').startOf('day').add(10, 'days').format('MMM Do YYYY');
const getDisplayName = (user) => {
  if (user.type === 'admin') {
    return 'Admin';
  } else if (user.type === 'guest') {
    return 'Guest'
  } else if(user.type === 'user') {
    return `${user.firstname} ${user.lastname}`
  } else {
    return 'No user'
  }
}

export {
  getNextDate,
  getDisplayName
}

我的 mocks 文件夹中还有一个 utils 文件的模拟,我在其中实现模拟返回值以进行测试。看起来像这样

// mock/utils.js
export const getNextDate = () => 'Oct 20th 2020';
export const getDisplayName = (user) => user

在我的组件和测试中,我正在做这样的事情

//Component.js
import React from 'react';
import { getNextDate, getDisplayName } from './utils'

export const Component = () => {
  const user = {
    type: 'admin',
    firstname: 'john',
    lastname: 'doe',
  }
  return (
    <div>
      <div>{getDisplayName(user)}</div>
      <div>{getNextDate(moment())}</div>      
    </div>
  )
}

// Component.test.js
import { Component } from '../Component'
jest.mock('./utils', () => require('./mock/utils'));

describe('Component', () => {
  beforeEach(() => {
    wrapper = shallow(
      <Component />
    );
  });

  it('renders next date', () => {
      // At this point, I want to change the mock return value of getNextDate to Dec 25th 2020 without changing it in mock/utils.js as other tests are using that value
      expect(wrapper.find('.date').text()).toEqual('Dec 25th 2020');
  });
});

但是,在其中一个测试用例中,我尝试更改 getNextDate 的模拟实现。由于我无法直接调用 getNextDate.mockImplementation(),因此如何完成此操作?

最佳答案

jest.mock('./utils', () => require('./mock/utils')) 重新发明了现有的 Jest 功能,__mocks__ manual mocks .

它应该是 __mocks__/utils.js 与原始模块处于同一级别,并使用 Jest spies 以使实现可更改:

export const getNextDate = jest.fn(() => ...);
export const getDisplayName = jest.fn(() => ...);

考虑到 __mocks__ 提供了默认的模拟,因此对于特定测试,不应使用 mockImplementation 覆盖它们,因为这会影响后续测试。相反,应该使用 *Once 来模拟特定调用。对于在 beforeEach 中指定且对多个测试通用的包装器:

import { getNextDate } from './utils';
jest.mock('./utils')

...

  beforeEach(() => {
    wrapper = shallow(<Component />); // uses default mock
  });

  it('renders next date', () => {
    getNextDate.mockReturnValueOnce(...);
    wrapper.setProps({}); // update with new mock
    expect(wrapper.find('.date').text()).toEqual('Dec 25th 2020');
  });

关于javascript - 如何更改 Jest 中模拟模块中函数的模拟实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64350855/

相关文章:

javascript - 无法在 jquery 中访问返回的 json

javascript - 如何使用drawImage/putImageData进行剪辑

javascript - jQuery:如何将可排序的 ('serialize' ) 数组从最后一个反转到第一个?

javascript - 使用 Jest 在另一个函数中测试一个函数

typescript - 用 Jest 测试 TypeScript : "no overload matches this call"

javascript,如何更改数组中元素的时间戳?

javascript - 期望不正确的智能感知方法

java - 对来自 jruby 的内部 java 方法调用设置 rspec 期望

python - 使用模拟第三方 API 的 Django/Python 测试

java - 如何使用 Junit 监视 Java 中的方法?