相关疑难解决方法(0)

如何使用jest在同一模块中模拟函数

正确模拟以下示例的最佳方法是什么?

问题是在导入时间之后,foo保持对原始未引用的引用bar.

module.js:

export function bar () {
    return 'bar';
}

export function foo () {
    return `I am foo. bar is ${bar()}`;
}
Run Code Online (Sandbox Code Playgroud)

module.test.js:

import * as module from '../src/module';

describe('module', () => {
    let barSpy;

    beforeEach(() => {
        barSpy = jest.spyOn(
            module,
            'bar'
        ).mockImplementation(jest.fn());
    });


    afterEach(() => {
        barSpy.mockRestore();
    });

    it('foo', () => {
        console.log(jest.isMockFunction(module.bar)); // outputs true

        module.bar.mockReturnValue('fake bar');

        console.log(module.bar()); // outputs 'fake bar';

        expect(module.foo()).toEqual('I am foo. bar is fake bar');
        /**
         * …
Run Code Online (Sandbox Code Playgroud)

javascript testing mocking jestjs

48
推荐指数
6
解决办法
1万
查看次数

用笑话和酶窥探 React 功能组件方法;无法窥探原始值

我正在尝试测试一个 React 组件并确保当它的按钮被点击时,正确的方法被调用。但是,当我尝试运行我的测试并尝试监视该方法时,我收到以下消息:

错误:无法监视原始值;给定的未定义

如何测试单击按钮时是否调用了正确的方法?谢谢!

示例组件.jsx:

import * as React from 'react';

const SampleComponent = () => {
  const sampleMethod = () => {
    console.log('hello world');
  };

  return <button onClick={sampleMethod} type="button">Click Me</button>;
};

export default SampleComponent;
Run Code Online (Sandbox Code Playgroud)

sampleComponent.test.jsx:

import * as React from 'react';
import { shallow } from 'enzyme';
import SampleComponent from './sample';

test('testing spy', () => {
  const spy = jest.spyOn(SampleComponent.prototype, 'sampleMethod');
  const wrapper = shallow(<SampleComponent />);
  wrapper.find('button').simulate('click');
  expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs enzyme

17
推荐指数
2
解决办法
1万
查看次数

标签 统计

jestjs ×2

enzyme ×1

javascript ×1

mocking ×1

reactjs ×1

testing ×1

unit-testing ×1