【发布时间】:2019-03-26 03:09:30
【问题描述】:
我想测试当令牌值为空时是否不调用库函数。为此,我必须在单元测试之间更改 GOOGLE_ANALYTICS_TRACKING_ID 的模拟值。它存储在 'config.js' 中,如下所示:
module.exports = {
GOOGLE_ANALYTICS_TRACKING_ID: process.env.GOOGLE_ANALYTICS_TRACKING_ID
};
它也被作为 HOC 的 withGoogleAnalytics 使用。在其中我以这种方式导入配置:
import { GOOGLE_ANALYTICS_TRACKING_ID } from 'config';
我的测试是这样的:
import React from 'react';
import { shallow } from 'enzyme';
import ReactGA from 'react-ga';
import withGoogleAnalytics from '../withGoogleAnalytics';
jest.mock('react-ga', () => ({
pageview: jest.fn(),
initialize: jest.fn()
}));
jest.mock('config', () => ({ GOOGLE_ANALYTICS_TRACKING_ID: '123' }));
const Component = withGoogleAnalytics(() => <div />);
describe('HOC withGoogleAnalytics', () => {
describe('render', () => {
const shallowWrapper = shallow(<Component />);
it('should fire initialize action', () => {
expect(ReactGA.initialize).toHaveBeenCalledWith('123');
});
it('should have pageview prop set', () => {
expect(shallowWrapper.prop('pageview')).toBe(ReactGA.pageview);
});
it('should not fire initialize action', () => {
expect(ReactGA.initialize).not.toHaveBeenCalled();
});
});
});
根据我在 StackOverflow 和 GitHub 上读到的内容,我应该可以使用 jest.resetModules() 和 jest.mockImplementation() 来做到这一点,但所有示例都是模拟函数。在这里,我需要在测试之间更改字符串值。我该怎么做?
【问题讨论】:
标签: reactjs testing mocking jestjs babel-jest