[英]jest.mock is not a function in react?
Could you please tell me how to test componentDidMount
function using enzyme
.I am fetching data from the server in componentDidMount
which work perfectly.Now I want to test this function. 您能否告诉我如何使用
enzyme
来测试componentDidMount
函数。我正在从componentDidMount
的服务器中获取数据,该函数运行正常。现在我要测试此函数。
here is my code https://codesandbox.io/s/oq7kwzrnj5 这是我的代码https://codesandbox.io/s/oq7kwzrnj5
componentDidMount(){
axios
.get('https://*******/getlist')
.then(res => {
this.setState({
items : res.data.data
})
})
.catch(err => console.log(err))
}
I try like this 我这样尝试
it("check ajax call", () => {
const componentDidMountSpy = jest.spyOn(List.prototype, 'componentDidMount');
const wrapper = shallow(<List />);
});
see updated code 查看更新的代码
https://codesandbox.io/s/oq7kwzrnj5 https://codesandbox.io/s/oq7kwzrnj5
it("check ajax call", () => {
jest.mock('axios', () => {
const exampleArticles:any = {
data :{
data:['A','B','c']
}
}
return {
get: jest.fn(() => Promise.resolve(exampleArticles)),
};
});
expect(axios.get).toHaveBeenCalled();
});
You look like you're almost there. 您看起来快要到了。 Just add the
expect()
: 只需添加
expect()
:
expect(componentDidMountSpy).toHaveBeenCalled();
If you need to check if it was called multiple times, you can use toHaveBeenCalledTimes(count)
. 如果需要检查它是否被多次调用,则可以使用
toHaveBeenCalledTimes(count)
。
Also, be sure to mockRestore()
the mock at the end to make it unmocked for other tests. 另外,请确保在
mockRestore()
对模拟进行嘲笑,以使其不受其他测试的影响。
List.prototype.componentDidMount.restore();
To mock axios
(or any node_modules
package), create a folder named __mocks__
in the same directory as node_modules
, like: 嘲笑
axios
(或任何node_modules
包),创建一个文件夹名为__mocks__
在同一目录node_modules
,如:
--- project root
|-- node_modules
|-- __mocks__
Inside of there, make a file named <package_name>.js
(so axios.js
). 在其中创建一个名为
<package_name>.js
的文件(即axios.js
)。
Inside of there, you'll create your mocked version. 在其中,您将创建模拟版本。
If you just need to mock .get()
, it can be as simple as: 如果只需要模拟
.get()
,它可以很简单:
export default { get: jest.fn() }
Then in your code, near the top (after import
s), add: 然后在代码的顶部附近(在
import
之后),添加:
import axios from 'axios';
jest.mock('axios');
In your test, add a call to axios.get.mockImplementation()
to specify what it'll return: 在您的测试中,添加对
axios.get.mockImplementation()
的调用以指定它将返回的内容:
axios.get.mockImplementation(() => Promise.resolve({ data: { data: [1, 2, 3] } });
This will then make axios.get()
return whatever you gave it (in this case, a Promise
that resolves to that object). 然后,这将使
axios.get()
返回您提供的任何内容(在这种情况下,该Promise
会解析为该对象)。
You can then do whatever tests you need to do. 然后,您可以进行所需的任何测试。
Finally, end the test with: 最后,结束测试:
axios.get.mockReset();
to reset it to it's default mocked implementation. 将其重置为默认的模拟实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.