我正在尝试在玩笑测试中计算出执行范围。
我有一个反应组件,在渲染期间执行以下行:
console.log(fun().m1());
这是三个笑话测试的例子
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import SimpleInput from './SimpleInput';
import { fun } from './util';
jest.mock('./util', () => ({
fun: jest.fn().mockImplementation(() => ({ m1: jest.fn() })),
}));
describe('SimpleInput', () => {
test("should have '' initialValue by default", () => {
const simpleInput = shallow(<SimpleInput />);
expect(simpleInput.prop('value')).toBe('');
});
});
结果:
TypeError: Cannot read property 'm1' of undefined
如果我将模拟实现移至以下位置:
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import SimpleInput from './SimpleInput';
import { fun } from './util';
jest.mock('./util');
describe('SimpleInput', () => {
fun.mockImplementation(() => ({ m1: jest.fn() }));
test("should have '' initialValue by default", () => {
const simpleInput = shallow(<SimpleInput />);
expect(simpleInput.prop('value')).toBe('');
});
});
结果:
TypeError: Cannot read property 'm1' of undefined
最后:
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import SimpleInput from './SimpleInput';
import { fun } from './util';
jest.mock('./util');
describe('SimpleInput', () => {
beforeEach(() => {
fun.mockImplementation(() => ({ m1: jest.fn() }));
});
test("should have '' initialValue by default", () => {
const simpleInput = shallow(<SimpleInput />);
expect(simpleInput.prop('value')).toBe('');
});
});
结果:通过。
我的问题是,如果我无法在 beforeEach 或每个特定测试用例之外执行模拟实现,我如何将以下内容添加到目前似乎失败的笑话设置文件中:
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener, // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
jest.spyOn
。这将在原始方法上添加一个间谍,然后您可以执行您需要的任何类型的模拟
let performanceNowSpy
beforeEach(() => {
performanceNowSpy = jest.spyOn(window.performance, 'now')
})
afterEach(() => {
performanceNowSpy.mockReset()
})
afterAll(() => {
performanceNowSpy.mockRestore()
})
test('meaningful test name', () => {
performanceNowSpy.mockReturnValueOnce(0)
// A simple example.
// `performance.now()` can be called from another module too.
expect(performance.now()).toBe(0)
})