React - 使用设置函数进行单元测试
React - unit testing with a setup function
我有以下情况:
describe('API - Input component', () => {
describe('Input element', () => {
it('should have a modifier to its class if data entered is erroneous', () => {
const wrapper = shallow(<Input error="Invalid data" />);
expect(wrapper.find('input').props().className).toBe('form-field__input form-field__input--error');
});
});
});
这很好用。只要我将一些数据传递给我的 error 道具,修饰符 class 应该是预期的并且测试通过。
现在,我想实现同样的事情,但要使用设置函数。像这样:
function setup () {
const props = {
error: {}
};
return shallow(<Input {...props} />);
}
describe('API - Input component', () => {
describe('Input element', () => {
it('should have a modifier to its class if data entered is erroneous', () => {
const wrapper = setup(how do I pass my props here?!);
expect(wrapper.find('input').props().className).toBe('form-field__input form-field__input--error');
});
});
});
谢谢!
const wrapper = setup(how do I pass my props here?!);
答案很简单,道具本身就是 文字对象 {prop1: value1, prop2: value2 ,... , propN: valueN}
:
const wrapper = setup({error: 'Invalid data'});
知道假设 setup
应该是:
function setup (props) {
return shallow(<Input {...props} />);
}
如果你想要设置中的默认道具,使用 Object.assign
来扩展设置中的默认道具与参数的道具。
function setup (props) {
const defaultPropsOfSetup = {
error : 'Invalid error'
};
props = Object.assign(defaultPropsOfSetup, props);
return shallow(<Input {...props} />);
}
我有以下情况:
describe('API - Input component', () => {
describe('Input element', () => {
it('should have a modifier to its class if data entered is erroneous', () => {
const wrapper = shallow(<Input error="Invalid data" />);
expect(wrapper.find('input').props().className).toBe('form-field__input form-field__input--error');
});
});
});
这很好用。只要我将一些数据传递给我的 error 道具,修饰符 class 应该是预期的并且测试通过。
现在,我想实现同样的事情,但要使用设置函数。像这样:
function setup () {
const props = {
error: {}
};
return shallow(<Input {...props} />);
}
describe('API - Input component', () => {
describe('Input element', () => {
it('should have a modifier to its class if data entered is erroneous', () => {
const wrapper = setup(how do I pass my props here?!);
expect(wrapper.find('input').props().className).toBe('form-field__input form-field__input--error');
});
});
});
谢谢!
const wrapper = setup(how do I pass my props here?!);
答案很简单,道具本身就是 文字对象 {prop1: value1, prop2: value2 ,... , propN: valueN}
:
const wrapper = setup({error: 'Invalid data'});
知道假设 setup
应该是:
function setup (props) {
return shallow(<Input {...props} />);
}
如果你想要设置中的默认道具,使用 Object.assign
来扩展设置中的默认道具与参数的道具。
function setup (props) {
const defaultPropsOfSetup = {
error : 'Invalid error'
};
props = Object.assign(defaultPropsOfSetup, props);
return shallow(<Input {...props} />);
}