【问题标题】:Mock rest API call using mockjax使用 mockjax 模拟休息 API 调用
【发布时间】:2014-08-04 13:15:11
【问题描述】:

我正在使用 ember-cli 开发 ember 应用程序和 ember-data,并通过对 rails 后端的 restful API 调用。

还使用 qunit 进行测试。 (https://github.com/appendto/jquery-mockjax 用于模拟 AJAX 请求)

在模拟 AJAX 请求时遇到问题

import Ember from "ember";
import DS from "ember-data";
import { test, moduleFor } from 'ember-qunit';
import startApp from '../../helpers/start-app';
var App;

module('Integration Test', {
  setup: function() {
    App = startApp();
    Ember.$.mockjax({
      url: '/api/v1/offers/1',
      type: 'GET',
      responseText: {
        offers: [{
          id: 1,
          state: 'draft'
        }]
      }
    });
  },

  teardown: function() {
    Ember.run(App, App.destroy);
  }
});

test('small test', function () {
  console.log("in")
  $.get('/api/v1/offers/1')
  console.log($.mockjax.mockedAjaxCalls().length);
  console.log("start")

  visit('/offers/1').then(function(){
    equal($('p.item_count').text(), "Offer Items(0)");
  });
  console.log($.mockjax.mockedAjaxCalls().length);
});

在控制台上它产生的输出为

in
MOCK GET: /api/v1/offers 
Object {url: "/api/v1/offers", type: "get", isLocal: false, global: true, processData: true…}
start
1 
1 

这里的 API 是使用 restful 适配器调用的,而不是使用模拟的 AJAX 调用。

我该如何解决这个问题?

【问题讨论】:

  • 您只模拟了其中一个 URL,您是否在其他地方模拟了 /offers/1 URL?如果没有,您需要将两者都添加到 Mockjax。

标签: jquery ember.js ember-data qunit mockjax


【解决方案1】:

使用 mockjax 拨打电话时。我们需要确保以下几点:

  • Adaptera/application.js 应该有

    if(window.app.environment === "test") {
      Adapter = DS.RESTAdapter.extend({ namespace: "ifany" });
    }
    
  • 使用 Ember-Cli ember-data-factory-guy 是一个不错的选择,并且还支持 mockAjax

  • 使用使用 FactoryGuy.buildList("user", 9) 的 FactoryGuy,您可以轻松获得 json 响应,并且 api 调用也可以正常工作

    $.mockjax({
      url: '/api/v1/offers/1',
      type: 'GET',
      responseText: {
      offers: Factory.buildList("offer",9)
      }
    });
    
  • 还要确保您在测试模式下运行应用程序

    ember server -environment=test
    

【讨论】:

  • 谢谢..这里不使用mockjax,现在改用ember-cli提供的api-stub
猜你喜欢
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多