【问题标题】:Jest spiedOn method is not called, but called once change the test case orderJest spyOn 方法没有被调用,而是在改变测试用例顺序后调用一次
【发布时间】:2020-05-11 17:17:54
【问题描述】:
  • 当测试处于第二个位置时,不会调用 Spied on 代码。 (或第二个render)并且测试用例失败
  • 如果测试用例位于第一个位置(或第一次渲染),则测试用例通过。

使用一个非常基本的 create-react-app OOTB 示例并为 MCVE 进一步简化:

MyModule.js

import React from 'react';
import someClass from './someClass';

function App() {
  someClass.track("someevent");
  return null;
}

export default App;

someClass.js

class SomeClass {
  constructor() {
    this.someProp = null;
  }
  getSatellite() {
      return {
        track: () => {}
      };
  }
  track(someProp) {
    ///THIS BELOW IF CLAUSE IS THE PROBLEM
    if (this.someProp === someProp) {
      return;
    } else {
      this.someProp = someProp;
    }
    ///////////////////////
    this.getSatellite().track('someevent');
  }
}

const instance = new SomeClass();

export default instance;

App.js

import React from 'react';
import MyModule from './MyModule'

function App() {
  return (
    <div className="App">
      <MyModule />
    </div>
  );
}

export default App;

App.test.js

import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
import someClass from './someClass';

test('renders learn react link', () => {
  render(<App />);
});

// it works if this test case is first one, weird :-| 
test('renders class', () => {
  const track = jest.fn();
  jest.spyOn(someClass, 'getSatellite').mockImplementation(()=>{
    console.log('here i am');
    return {
      track
    }
  })
  render(<App />);
  expect(track).toHaveBeenCalledTimes(1);
});

输出:

  ✓ renders learn react link (17ms)
  ✕ renders class (5ms)

  ● renders class

    expect(jest.fn()).toHaveBeenCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

      18 |   })
      19 |   render(<App />);
    > 20 |   expect(track).toHaveBeenCalledTimes(1);
         |                 ^
      21 | });
      22 | 

      at Object.<anonymous> (src/App.test.js:20:17)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        10.472s

如果您需要 cmets 中的任何内容,请告诉我。

【问题讨论】:

    标签: node.js reactjs jestjs


    【解决方案1】:

    在第一个render(&lt;App /&gt;) 中,someClasssomeProp 被设置为someevent

    现在在下一次渲染中,我只是模拟函数调用,而不是重置someProp。这就是if (this.someProp === someProp) 生效的原因。

    所以我需要将someProp 重置为另一个值或null,它会正常工作。

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2019-10-08
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2019-12-12
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多