angular - 无法读取未定义测试的属性 'MobileServiceClient'

标签 angular azure testing karma-jasmine

我正在尝试测试我的组件,该组件的构造函数已注入(inject)名为 AzureService 的服务

这是组件片段:

constructor(private azureService: AzureService) { }

这是规范文件:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        DashbaordComponent,
        StatusComponent
      ],
      providers:[ AzureService]
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(DashbaordComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

这是服务:

export declare var WindowsAzure;
@Injectable()
export class AzureService {
constructor() { this.client = new WindowsAzure.MobileServiceClient(this.azureUrl); }
}

我无法理解为什么在index.html文件中导入的Azure-Apps-Client库并不重要:

<script src="//zumo.blob.core.windows.net/sdk/azure-mobile-apps-client.2.0.0.js"></script>

有没有办法在运行测试之前加载这个库?

这有什么线索吗?

更新:这是测试失败的原因: enter image description here

更新:这是组件代码:

  getModules() {
        this.result.updateInfo("Getting classes...")

        this.azureService.getProgrammesByWrapper().then(((res) => {
            this.result.updateInfo("Sorting classes...")
            this.displayModules(res);
            this.result.updateSuccess(true);
        }));
    }

最佳答案

推荐的方法by Google ,而不是使用实际的服务,是使用测试替身来进行单元测试组件。虽然加载所需的库似乎很有意义,但单元测试实际上应该只专注于测试组件代码。

A component-under-test doesn't have to be injected with real services. In fact, it is usually better if they are test doubles (stubs, fakes, spies, or mocks). The purpose of the spec is to test the component, not the service, and real services can be trouble.

要创建服务的测试替身 stub ,请在 .spec 文件中定义一个普通的旧 JavaScript 对象,其中包含组件所需的函数或属性在这种情况下工作,如下所示:

const exampleServiceStub = {
  getProgrammesByWrapper(): Promise<Module[]> {
    return Promise.resolve([
      { id: 1, title: "Test Module 1", description: "Example description." },
      { id: 2, title: "Test Module 2", description: "Example description." }
    ]);
  }
}

您可以配置测试替身来测试您想要的服务的确切状态,或稍后对其进行操作。然后将您的测试替身服务列为提供者以代替您的实际服务:

TestBed.configureTestingModule({
   declarations: [ ExampleComponent ],
   providers:    [ {provide: ExampleService, useValue: exampleServiceStub } ]
});

如果您需要在测试中引用您的服务,请确保get it from the injector .

更新: 您可以查看我在 Github 上整理的示例证明这一点:component/service/test with a mock service .

祝你好运!

关于angular - 无法读取未定义测试的属性 'MobileServiceClient',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44649963/

相关文章:

angular - 在上一个完成后调用行中的过滤器方法

c# - 如何在客户端不发送任何请求的情况下从 Windows Azure 服务器向客户端移动应用程序(iOS)发送消息?

c# - Azure Web App 跟踪日志未出现在日志中

java - 覆盖 Java System.currentTimeMillis 以测试时间敏感代码

symfony - 为硬删除记录禁用软删除过滤器不起作用

javascript - anchor href 与 angular routerlink

angular - 如何在angular4中上传同一个文件

azure - 通过azure数据工厂将数据从oracle复制到azure blob存储

java - 多次运行同一个 Gradle 任务

javascript - 带有监视任务的 Lerna - lerna run --parallel