模拟Axios拒绝休息呼叫

uwopmtnx  于 2022-11-29  发布在  iOS
关注(0)|答案(1)|浏览(104)

我有一个实用程序类:
utils.ts

import axios, { AxiosResponse } from 'axios';
import { throwError } from 'rxjs';

axios.defaults.withCredentials = true;
axios.defaults.responseType = 'json';

export class UserUtils {

    public updateUserData(data) {
        return axios.post('http://mock.rest.server.com:1234/rest/update/user/', data, 
            {
                withCredentials: true,
                responseType: 'json' as 'json
            })
            .then(resp => {
                return resp;
            })
            .catch(error => {
                return throwError('error updating user data');
            });
    }

}

我的组件类按照以下方式调用上面的代码:
userComponent.ts

export class UserComponent {
    import { UserUtils } from './utils';
    

    public userUtils: UserUtils = new UserUtils();

    // Btn click method
    public update(content) {
        this.userUtils.updateUserData(content) // <-- call made here
           .then((data) => {

               this.showSuccessModal(); // <- trying to test this

           }, (err) => {

               this.showErrorModal(error); // <- trying to test this

           });
    }

}

我正在尝试对userComponent测试肯定(showSuccessModal)/否定(showErrorModal)方案。ts
userComponent.spec.ts

import { UserComponent } from '../../../user/userComponent';
import { UserUtils } from '../../../user/utils';

 describe('User Comp test', () => {

     beforeAll(done => (async () => {

         Testbed.configureTestingModule({
             declarations: [
                 UserComponent
             ]
         });
         await TestBed.compileComponents();
     })().then(done).catch(done.fail);

     describe('User Comp (with beforeEach)', () => {
         let component: UserComponent;
         let fixture: ComponentFixture<UserComponent>;

         beforeEach(() => {                 
             fixture = await TestBed.createComponent(UserComponent);
             component = fixture.componentInstance;
         });

         it('should show error modal', () => {
             let errorModal = spyOn(component, 'showErrorModal');
             spyOn(component.userUtils, 'updateUserData').and.returnValue(Promise.reject('error updating'));

             component.update({test: 'test');
             expect(errorModal).toHaveBeenCalled();
         });
     });
 }

但是,在运行测试时,我看到:

Error: Expected spy showErrorModal to have been called
    at <Jasmine>

看样子在测试中,这条“成功”路线它总是叫得上号。

e4eetjau

e4eetjau1#

我觉得

.catch(error => {
    return throwError('error updating user data');
});

解决是可观察的,你尝试:

.catch(error => {
    throw 'error updating user data';
});

相关问题