我有一个JSX文件来编写。
../dist/container/index
constructor(props) {
super(props);
this.state = {
showName: null
}
}
componentWillMount() {
Request
.get('/api')
.end((err, res) => {
if (res) {
this.setState({
showName: res.name
});
}
});
}
render (
let { showName } = this.state;
render (
{showName ? <div> showName</div> : <div>No Name</div> }
)
)
测试文件中的,
import landing from '../dist/container/index’;
describe(‘landing’, () => {
it(‘check’, () => {
jest.mock('../dist/container/index’, () => {});
landing.componentWillMount = jest.fn().mockImplementation(() => { return { 'a': '2'} });
const lands = shallow(<landing productDetails={productDetail} messages={messages}/>);
expect(lands.componentWillMount()).toBeCalledWith({‘a’: '2'});
})
});
我得到了下面的错误。
预期(jest.fn()).not.toBeCalledWith() jest.fn()值必须是模拟函数或间谍。接收:对象:{"a":"2"}
我想要模拟整个组件的威尔挂载调用,并需要得到showName,但我总是没有名字。有支持吗?
发布于 2018-02-18 11:06:24
下面是一个使用Jest的粗略示例。它直接使用内置的取API,并模拟使用jest的mockImplementation
。
我假设您正在使用酶验证组件输出。
Landing.jsx
import React from "react";
import { render } from "react-dom";
export class Landing extends React.Component {
constructor(props) {
super(props);
this.state = {
showName: null
};
}
componentDidMount() {
fetch("/api", {
method: 'GET'
})
.then(res => {
this.setState({
showName: res.name
});
})
.catch (err => { /* do something */ });
}
render() {
const { showName } = this.state;
const displayName = showName ? showName : "No Name";
return <div id='show'>{displayName}</div>;
}
}
Landing.spec.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Landing, http } from "./landing";
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
describe("<Landing />", () => {
let wrapper;
describe("when api returns successfully", () => {
beforeEach(() => {
window.fetch = jest.fn().mockImplementation(() => {
return Promise.resolve({
name: 'foo'
})
})
wrapper = shallow(<Landing />);
})
it ('should render foo', () => {
expect(wrapper.update().find('div').text()).toEqual('foo')
});
});
describe("when api returns unsuccessfully", () => {
beforeEach(() => {
window.fetch = jest.fn().mockImplementation(() => {
return Promise.reject("err")
})
wrapper = shallow(<Landing />);
})
it ('should render No Name', () => {
expect(wrapper.update().find('div').text()).toEqual('No Name')
});
});
});
https://stackoverflow.com/questions/48852923
复制相似问题