gpt4 book ai didi

javascript - 为什么 Jest/Enzyme 跟踪/聆听 componentDidMount 或任何 React 无法正常运行?

转载 作者:行者123 更新时间:2023-12-02 21:15:59 26 4
gpt4 key购买 nike

我编写了一个函数,可以成功测试 componentDidMount 何时触发。但由于某种原因,使用相同的逻辑来测试其相邻方法是否已被触发是行不通的。不知道为什么?谁能告诉我我的误解是什么?

//Account.js

...
componentDidMount() {
this.checkData();
}

checkData = () => {
console.log('i am a check data method that needs testing');
}
...

//开 Jest

// this works
it('should call the CDM function', () => {
const instance = mountedComponent.instance();
jest.spyOn(instance, 'componentDidMount');
instance.componentDidMount();
expect(instance.componentDidMount).toHaveBeenCalledTimes(1);
})

// Attempt 1 - this fails "Cannot spy the checkData property because it is not a function; undefined given instead"

it('should call the `checkData` function', () => {
const instance = mountedComponent.instance();
jest.spyOn(instance, 'checkData');
instance.componentDidMount();
expect(instance.checkData).toBeCalledTimes(1);
})

// Attempt 2 - also fails "Received number of calls: 0"

it('should call the `checkData` function', () => {
const instance = mountedComponent.instance();
instance.checkData = jest.fn();
instance.componentDidMount();
expect(instance.checkData).toBeCalledTimes(1);
})

为什么实例中会存在 CDM 而不是 checkData ?>

最佳答案

因此,最好的方法是检查结果,而不是专门检查函数调用。

checkData 实际在做什么(您尚未显示)。它是否调用了另一个文件中的某些内容?

如果是这样,请模拟其他文件中的函数以返回一些数据,并验证在安装组件时是否调用了模拟函数。

例如:

// component file
import { someMethod } from 'someModule';

export class MyComponent extends React.Component {

async checkData() {
await someMethod();
}

componentDidMount() {
this.checkData();
}

render() {

}
}
// in your spec file
import { someMethod } from 'someModule';

jest.mock('someModule');


someMethod.mockImplementation(() => {
// do whatever you want here
});

// do your all your normal setup, probably something like this
let mountedComponent;
beforeEach(() => {
mountedComponent = mount(...);
});

// clear the mock after each mount
afterEach(() => someMethod.mockClear());

it('should do things',() => {
expect(someMethod).toHaveBeenCalled();
});

关于javascript - 为什么 Jest/Enzyme 跟踪/聆听 componentDidMount 或任何 React 无法正常运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60969691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com