当前位置: 首页 > 知识库问答 >
问题:

预期间谍导航已被调用 [ [ '/ProjectData/MasterSequence']]但它从未被调用

史淇
2023-03-14

我正在为Angular7模板中的函数编写单元测试用例。它是一个登录组件,登录功能在http请求中具有router.navigate,以便在正确登录时路由到仪表板。但是我得到了错误 -

错误:应使用[['/ProjectData/MasterSequence']]调用spy navigate,但从未调用过。堆叠(http://localhost:9876/absolute/home/hp/Downloads/ICICI/ICICI_UI/node_modules/jasmine-core/lib/jasmine核心/jasmine。js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:2455:17)在构建预期结果(http://localhost:9876/absolute/home/hp/Downloads/ICICI/ICICI_UI/node_modules/jasmine-core/lib/jasmine核心/jasmine。js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:2425:14)规格预期结果工厂(http://localhost:9876/absolute/home/hp/Downloads/ICICI/ICICI_UI/node_modules/jasmine-core/lib/jasmine核心/jasmine。js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:901:18)在规范中添加预期结果(http://localhost:9876/absolute/home/hp/Downloads/ICICI/ICICI_UI/node_modules/jasmine-core/lib/jasmine核心/jasmine。js?0B1EAF7A13CAE32191EAD482CFC96AE41FC22B:524:34)。AddExpectionResult(http://localhost:9876/absolute/home/hp/Downloads/ICICI/ICICI_UI/node_modules/jasmine-core/lib/jasmine核心/jasmine。js?0B1EAF7A13CAE32191EAD482CFC96AE41FC22B:845:21)。与(http://localhost:9876/absolute/home/hp/Downloads/ICICI/ICICI_UI/node_modules/jasmine-core/lib/jasmine核心/jasmine。js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:2369:12)。(http://localhost:9876/src/app/authentication/login2/login2.component.spec.ts?:208:38)

应用程序组件.html

loginData(value) {
    this.username = value.username;
    this.password = value.password;
    this.dataObj = {
      'username': this.username,
      'password': this.password
    }
    this.loginService.login(this.dataObj).then((data) => {
      console.log("data", data);
      this.response = data;
      console.log("message", this.response.message);
      if (this.response.message == "Login Successful.") {
        this.router.navigate(['/ProjectData/MasterSequence'])
      }
      else {
        this.toastr.error("UserName or Password is incorrect");
      }
    })

app.component.spec.ts

describe('Login2Component', () => {
    let comp: Login2Component;
    let fixture: ComponentFixture<Login2Component>;
    let de: DebugElement;
    let el: HTMLElement;
    beforeEach(async(() => {
        mockRouter = { navigate: jasmine.createSpy('navigate') };
        TestBed.configureTestingModule({
            declarations: [Login2Component, MasterSequenceComponent],

            imports: [
                BrowserModule,
                FormsModule,
                RouterModule,
                ReactiveFormsModule,
                RouterTestingModule,
                HttpClientModule,

                [
                    RouterTestingModule.withRoutes([
                        { path: '/ProjectData/MasterSequence', 
                          component: MasterSequenceComponent }
                    ])
                ]
            ],
            schemas: [CUSTOM_ELEMENTS_SCHEMA],

            providers: [{ provide: ToastrService, useValue: ToastrService }, Login2Service]
        })
            .compileComponents()
            .then(() => {
                //Login2Component
                fixture = TestBed.createComponent(Login2Component);

                comp = fixture.componentInstance;

                de = fixture.debugElement.query(By.css('form'));
                el = de.nativeElement;
            });
    }));

    it('should redirect the user to "login form" component when button is clicked', () => {
        const router = TestBed.get(Router);
        const spy = spyOn(router, 'navigate');
        fixture.detectChanges();

        const button = fixture.debugElement.query(By.css('form[id=loginform]'));

        button.triggerEventHandler('click', null);

        let userN = comp.addLoginData.controls['username'];
        userN.setValue('pallavi');
        let pass = comp.addLoginData.controls['password'];
        pass.setValue(1234);

        let value = {
            username: userN,
            password: pass
        };

        comp.loginData(value);

        expect(spy).toHaveBeenCalledWith(['/ProjectData/MasterSequence']);
    });
});

参考资料 -

角度2/4/6/7-使用路由器进行单元测试

使用此代码时的进一步错误 -

it('should redirect the user to "login form" component when button is clicked', () => {
    let value = {
         username: 'user123',
         password: 'pwd'
     };
     comp.username = '';
     comp.password = '';

     spyOn(comp.LoginService,'login').and.callThrough();

    comp.loginData(value);
     expect(comp.username).toBe('user123');
     expect(comp.password).toBe('pwd');
     expect(comp.LoginService.login).toHaveBeenCalledWith(value)

//expect(RouterMock.navigate).toHaveBeenCalledWith(['/ProjectData/MasterSe//quence']);
    });

错误:“未处理的promise拒绝:”,HttpErrorResponse{headers:HttpHeaders{normalizedNames:Map{},lazyUpdate:null,he-aders:Map{}},状态:0,状态文本:“未知错误”,url:'http://192.168.5.128:3002/api/user/login,确定:false,名称:'HttpErrorResponse',消息:'Http失败响应http://192.168.5.128:3002/api/user/login:0未知错误,错误:ProgressEvent{isTrusted:true}};区域:','代理区域',';任务:','promise。然后是',';值:‘,HttpErrorResponse{headers:HttpHeaders{normalizedNames:Map{},lazyUpdate:null,headers:Map}},状态:0,状态文本:“未知错误”,url:'http://192.168.5.128:3002/api/user/login,确定:false,名称:'HttpErrorResponse',消息:'Http失败响应http://192.168.5.128:3002/api/user/login:0未知错误,错误:ProgressEvent{isTrusted:true}},未定义

共有1个答案

谭坚诚
2023-03-14

我找不到< code > loginservice . log in()的代码,但我确信它一定在进行一些API调用,因此创建< code >存根是一个好的做法。类似于:

export class LoginServiceStub{
  login(obj){
     return new Promise((resolve, reject) => {
         resolve("whatever_data_is_expected");
     });
   }
}

在< code>spec文件中:

describe('Login2Component', () => {
  let RouterMock = {
    navigate: jasmine.createSpy('navigate')
  };

 beforeEach(async(() => {
        mockRouter  = { navigate: jasmine.createSpy('navigate') };
        TestBed.configureTestingModule({
        decleration: [ .... ],
        providers: [
             {provide: ToastrService, useValue: ToastrService }, // I am not sure why you have done "useValue" with same Service
             {provide: Login2Service, useClass: Login2ServiceStub },
             {provide: Router, useValue: RouterMock  }
             ], 
      // ... and other deceleration of Test Bed
  )};

})

然后在其中阻止:

it('should redirect the user to "login form" component when button is clicked', () => {
       let value = {
            username: 'user123',
            password: 'pwd';
        };
        comp.username = '';
        comp.password = '';
        spyOn(comp.loginService,'login').and.callThrough();
        comp.loginData(value);
        expect(comp.username).toBe('user123');
        expect(comp.password).toBe('pwd');
        expect(comp.loginService.login).toHaveBeenCalledWith(value)
        expect(RouterMock.navigate).toHaveBeenCalledWith(['/ProjectData/MasterSequence']);
    });
});

我还建议您阅读这篇专为Angular中的单元测试编写的文章集。您可以找到涵盖几乎所有基本测试场景的几个链接。

 类似资料:
  • 我在一个项目上实现了一个简单的集成测试,但是失败了,因为预期()行在component.save()方法之前执行。当我把预期()行放在setTimeout()上时,它成功了。没有setTimeout()如何成功? spec.ts 错误:

  • 我是写测试和使用Mockito的新手。我在Stackoverflow上阅读了类似的主题,并做了建议的更改,确保所考虑的类/接口/方法是开放的。 我试图跟踪这个 模仿构造函数注入的依赖项 这是我目前想出来的测试 但我一直得到的回应是 即使我在测试中没有提到这种方法,我也得到了这种反应。这是我的演示者注册方法。我已经改变了类/接口 同样地 这里是接口 感谢您的帮助。

  • 我的从未被调用,即使我在inapp对话框中单击立即购买,logcat也不会打印任何内容。

  • 问题:为什么从不调用? 我在xml配置中扩展了,如 MyEntityManagerFactoryBean MyInterceptor: 更新:[解释为什么自定义脏政策看起来不像我的方式] 我希望每次更改实体中的内容时更新时间戳,但除外。同时,应该是持久的,而不是暂时的(意味着导致实体变脏)。 由于我使用Spring事务和Hibernate模板,有一些细微差别: 1) 我无法在每个setter的末尾

  • 问题内容: 我有一个非常简单的Servlet和一个非常简单的HttpSessionListener: 我的方法从未被调用(没有日志输出),最终我在调用getSession()的那一行上得到一个 我尝试拨打电话时也没有问题,但存在相同的问题。 我不明白- 注释不足以调用我的侦听器吗?Eclipse甚至在下方将其显示为侦听器。 问题答案: 原来这是愚蠢的Eclipse问题之一… Project-> C

  • 我已经读了很多关于这个错误的答案,但我没有找到解决方案,也许类对象不一样 我的错误是: 通用域名格式。谷歌。格森。JsonSyntaxException:java。lang.IllegalStateException:应为字符串,但为BEGIN_对象 所以,我只是想从JSON中获取一个对象,如下所示: 我的JsonObject是: 我的不同POJO(我不把get和set简称为代码): 这是完整的堆