javascript - 测试 $state.go 的自定义方法

标签 javascript angularjs meteor jasmine angular-mock

我尝试测试这段代码:

redireccion() {
this.$state.go('modifyLine', {lineId: this.look()._id});
}

look() {
return Entries.findOne({name: this.entry.name});
}

上面的代码方法没问题(看),但是对于“redireccion”,我尝试了类似的方法,但出现了错误。

这是代码:

    describe('redireccion()', () => {
      beforeEach( inject(($state) => {
      spyOn($state, 'go');
      spyOn(controller, 'look');
      spyOn(Entries, 'findOne');
      }));

    it('should be a ... bla bla', () => {
    controller.redireccion();
    expect($state.go).toHaveBeenCalledWith('modifyLine', {lineId: });
    });
   });

这是摘录,因为我真的不知道如何测试它。

最佳答案

我会尽力为您提供见解。您应该尝试使您的测试隔离...这意味着如果您正在测试重定向,您可以模拟 Look 方法,因为它不相关(对于此特定测试)。

 describe('testing redirection()', () => {
       beforeEach( inject(($state) => {
            //here I'm saying that I'm spying every call to $state.go
            spyOn($state, 'go');

            //And here I'm that I'm not only spying every call to 
            //controller.look() but I'm also replacing the original
            //implementation with my fake one. Every call will basically 
            //return an object with id equals 10
            spyOn(controller, 'look').and.callFake(() => {
                 var mockedLine = {
                     _id: 10
                 };
                 return mockedLine;
            });
       }));

       it('should call state.go', () => {
            controller.redireccion();

            //if you just want to check if the method was called, do the following:
            expect($state.go).toHaveBeenCalled();

            //if you need to also check the arguments, try:
            var args = $state.go.mostRecentCall.args;
            expect(args[0]).toBe('modifyLine');
            expect(args[1].lineId).toBe(10);
       });
  });

关于javascript - 测试 $state.go 的自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39336220/

相关文章:

javascript - Meteor 的 blaze 和 Famo.us 如何一起玩?

javascript - 饼图系列颜色在 NodeRed 上为黑色

javascript - 找不到 Angular 2.2.0 平台浏览器动态 Bootstrap

android - 请推荐 ionic 应用程序模板

javascript - meteor 角色 : Can't mix grouped and non-grouped roles

meteor - 如何清理 Meteorjs 应用程序的开发版本?

javascript - 为什么selector.text会得到一个内部函数值?

javascript - 为简单项目运行 webpack 脚本时出错

javascript - 带有 "restrict"和不带 "restrict"的 Angular Directive(指令)

javascript - Angular.js HTTP 获取使用 $routeParams