mog*_*oli 2 javascript mocking reactjs jestjs
我试图用Jest模拟react-dom模块
import React from 'react';
import {configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Link from '../components/DumbComp';
import { shallowToJson } from 'enzyme-to-json';
import { render } from 'react-dom';
configure({ adapter: new Adapter() });
jest.mock('react-dom');
describe('Link',() =>{
it('should render correctly', ()=>{
expect(render).toHaveBeenCalledWith(
<Link title="mockTitle" url="mockUrl" />, 'element-node'
);
expect(render).toHaveBeenCalledTimes(1);
});
});
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,我收到以下错误:
Link › should render correctly
expect(jest.fn()).toHaveBeenCalledWith(expected)
Expected mock function to have been called with:
[<Link title="mockTitle" url="mockUrl" />, "element-node"]
But it was not called.
Run Code Online (Sandbox Code Playgroud)
似乎当我模拟渲染方法时,它不返回任何东西.有关如何正确嘲笑它的任何想法.
我正在使用本教程:https://medium.com/wehkamp-techblog/unit-testing-your-react-application-with-jest-and-enzyme-81c5545cee45
根据"嘲弄的艺术"部分.
谢谢
如果你想在同一个文件中创建一个手动模拟创建,如下所示:
jest.mock('react-dom', () => ({
render: jest.fn(),
}));
Run Code Online (Sandbox Code Playgroud)
我建议你看一下快照,然后用它来与enyzme一起使用.它使测试更容易,因为你可以写这样的东西:
describe ('Link',() =>{
it ('should render correctly', ()=> {
const component = mount(
<Link title="mockTitle" url="mockUrl" />
);
expect(component).toMatchSnapshot();
});
});
Run Code Online (Sandbox Code Playgroud)
这将为您提供组件如何精确渲染的快照.您还可以将它与您测试的函数一起使用,它将为您提供函数调用的所有调用的快照以及函数调用的参数.
| 归档时间: |
|
| 查看次数: |
3395 次 |
| 最近记录: |