【问题标题】:jasmine httpbackend any url to return mock datajasmine httpbackend 任何 url 以返回模拟数据
【发布时间】:2016-05-19 18:18:50
【问题描述】:

我正在使用 Jasmine 为我的 Angular 应用程序构建一个测试。

我想模拟 api 调用以返回一些数据,但我的控制器上的 api 调用是

$scope.getSubjects = ->
  $http.get "/api/students/#{$scope.freshBooking.StudentId}"
  .then (response) ->
    $scope.subjects = response.data.Subjects

在我的测试中,我有

@httpBackend.whenGET(/^\/api\/students/.*/).respond ->
  [200, {data: 'subjects'}]

it 'should have data in subjects', ->
  expect(@scope.subjects).toBeUndefined()
  @scope.getSubjects()
  @httpBackend.flush()
  expect(@scope.subjects).toBeDefined()

我收到一条错误消息,提示“预期未定义要定义”。所以我猜我没有为 api 调用返回任何数据。

我将如何让它发挥作用?我的正则表达式不正确吗?

【问题讨论】:

    标签: angularjs unit-testing coffeescript


    【解决方案1】:

    正则表达式似乎不正确。尝试关注

    ^\/api\/students\/.*
    

    在“students”之后添加斜杠以转义正斜杠,将斜杠末尾的斜杠删除到正则表达式,因为实际的 API 调用末尾没有斜杠。

    进一步的正则表达式组可用于提取学生 ID

    \/api\/students\/#(.*)  //The brackets group would extract Student ID
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多