我想测试在单击按钮时启动的 fetch API 的 post 请求。为了模拟 fetch api 请求,我正在使用该sinon库。假服务器是活动的,但不提供响应 JSON 对象。在apiUrl这里http://localhost:5000/api/users和用户数据的{ sid: 1, sname: 'test'}。
这是 App.test.js 文件
describe('test api',()=>{
let server;
beforeEach(() => {
server = fakeServer.create();
server.respondWith('POST',
apiUrl,
[
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(userData)
]
);
});
describe('app component', () => {
const app = mount(<App />);
beforeEach(() => {
app.find('Button').simulate('click');
});
it('get data from server', done => {
server.respond();
setTimeout(done);
});
it('updates state', () => {
expect(app.state().user).toEqual('user1') // …Run Code Online (Sandbox Code Playgroud) ngOnInit(): void {
this.formBuilder.group({
nameFormCtrl: ['', this.validateName],
});
}
validateName(c: FormControl) {
return c.value === this.name ? null : {
validateName: {
valid: false
}
};
}
Run Code Online (Sandbox Code Playgroud)
这里this.name应该引用组件,而不是引用undefined
我正在基于切换值创建表单组验证
public toggle:boolean=false;
ngOnInit(): void {
this.formGroup = this.formBuilder.group({
formArray: this.formBuilder.array([
this.formBuilder.group({
toggleFormCtrl: [this.toggle, null],
fnameFormCtrl: ['', this.checkInputs.bind(this)],
lnameFormCtrl: ['', this.checkInputs.bind(this)],
addressFormCtrl: ['', this.checkMiInput.bind(this)]
}),
])
});
}
checkInputs(c: FormControl) {
if (this.toggle) {
return c.value === '' ? null : {
checkinputs: {
valid: false
}
};
} else {
return c.value ? null : {
checkinputs: {
valid: false
}
};
}
}
checkMiInput(c: FormControl) {
if (this.toggle) {
return c.value ? null : {
checkMiInput: {
valid: …Run Code Online (Sandbox Code Playgroud) javascript ×3
angular ×2
form-control ×2
typescript ×2
enzyme ×1
jestjs ×1
reactjs ×1
sinon ×1