Jasmine 2.0 async done()和angular-mocks inject()在同一个测试中()

hus*_*007 59 javascript unit-testing mocking jasmine angularjs

我通常的测试用例看起来像

it("should send get request", inject(function(someServices) {
     //some test
}));
Run Code Online (Sandbox Code Playgroud)

并且Jasmine 2.0异步测试看起来应该是这样的

it("should send get request", function(done) {
     someAsync.then(function(){
         done();
     });
});
Run Code Online (Sandbox Code Playgroud)

如何在一次测试中同时使用done和inject?

Sco*_*ing 78

这应该工作; 我更新到Jasmine 2.0时遇到了同样的问题

it("should send get request", function(done) {
    inject(function(someServices) {
        //some async test
        done();
    })(); // function returned by 'inject' has to be invoked
});
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,这不起作用.`inject`中的代码永远不会被调用. (4认同)
  • 这不适合我.`inject`的返回值是一个函数,需要调用. (4认同)
  • @WhiteAngel @dokkaebi在给出的代码示例中,立即调用从`inject`返回的方法.这非常重要!如果您在最后忘记了这两个问题,则不会执行您的测试代码. (2认同)

Ari*_*ner 20

重要注意事项是inject通话后的括号.例如.

inject(function(someServices) {
   //some async test
   done();
})();  <-- these brackets here important.
Run Code Online (Sandbox Code Playgroud)

如果你看看的类型inject:

export declare function inject(tokens: any[], fn: Function): () => any;
Run Code Online (Sandbox Code Playgroud)

你可以看到它返回一个函数,所以你没有输出,因为你忘了调用函数!

如果你考虑一下,它返回一个函数是有道理的,因为it它需要一个函数!

所以额外的括号应该解决所有问题!

工作实例:

  it('should allow you to observe for changes', function(done) {
    inject([GlobalStateService], (globalStateService: GlobalStateService) => {
      globalStateService.observe("user", storageType.InMemoryStorage, (user: string) => {
        expect(user).toBe("bla");
        done();
      });

      globalStateService.write({ user: "bla"}, storageType.InMemoryStorage);
    })();
  });
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是一个答案.在任何情况下,评论都会太长. (2认同)

小智 12

添加@Scott Boring的答案和@WhiteAngel的评论,他们提到了注入中的代码从未被调用过.

这对我有用:

it("should send get request", function(done) {
    inject(function(someServices) {
       //some async test
       done();
    })();
});
Run Code Online (Sandbox Code Playgroud)

  • 我用这个得到`注入不是函数` (3认同)