首页 > 解决方案 > Reactjs 功能组件中的 Jest SpyOn

问题描述

我正在尝试 SpyOn 一个 reactJS 功能组件内的功能。我已经看到了一些答案,并且开始了解我们将函数作为道具传递给我们的组件的过程。但这种方法对我不起作用。所以我尝试使用 const spy = jest.spyOn(App.prototype, "sampleFunctionName"); As Expected 它会抛出一个错误,说sampleFunctionName是未定义的,因为 App.prototype 不包含它。所以为了克服这个我添加sampleFunctionName到 App.prototype asApp.prototype.sampleFunctionName = jest.fn()并尝试将它作为

wrapper = shallow(<App {...props} />);
wrapper.find("#btn-id").simulate("click")
expect(spy).toHaveBeenCalled()

现在的问题是 spy 被调用的次数总是为零。所以我想知道我尝试过的是否正确或任何其他方法来监视无类组件中的函数

下面是一个示例来演示上述要求:

function App(props){
  function save(){
    //contains the code for api calls and store changes
  }
  return(
    <Button id = "btn-id" onClick = {save}>Name</Button>
  )
}

测试文件会是这样的:

import React from "react";
import { shallow } from "enzyme";
import {App} from './App'
describe('desc',() =>{
      ...
      const spy = jest.spyOn(App.prototype, "save");
      //using the above spy says "save" is undefined so added this line before using spy
      // App.prototype.save = jest.fn()

      wrapper = shallow(<App {...props} />);
      wrapper.find("#btn-id").simulate("click")
      expect(spy).toHaveBeenCalled()
})

标签: javascriptreactjsunit-testingjestjsenzyme

解决方案


您不能模拟或监视save函数,它是App构造函数中的私有函数,而不是 App 实例的方法,这意味着save函数在 App 的原型中不存在。您应该模拟或监视函数内部的save函数,即为您的案例进行 api 调用的函数/方法。这是单元测试解决方案:

例如

index.js

import React from 'react';

export function App(props) {
  function save() {
    // contains the code for api calls and store changes
    console.log('You should spy or mock the function which make the api calls');
  }
  return (
    <button id="btn-id" onClick={save}>
      Name
    </button>
  );
}

index.test.js

import React from 'react';
import { shallow } from 'enzyme';
import { App } from './';

describe('61174416', () => {
  it('should pass', () => {
    const logSpy = jest.spyOn(console, 'log');
    const props = {};
    const wrapper = shallow(<App {...props} />);
    wrapper.find('#btn-id').simulate('click');
    expect(logSpy).toHaveBeenCalled();
  });
});

覆盖率 100% 的单元测试结果:

 PASS  stackoverflow/61174416/index.test.tsx (8.332s)
  61174416
    ✓ should pass (19ms)

  console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
    You should spy or mock the function which make the api calls

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.395s

将 替换为console.log进行 api 调用的函数或方法。

源代码:https ://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61174416


推荐阅读