标签: sinon

undefined | 0 | ReferenceError:严格模式禁止隐式创建全局属性'csrf_token'

所以,这是我遇到的一个非常有趣的问题.

我目前正在构建一个backbone.js - Rails应用程序.通常只是为了学习目的而构建它.我(就像任何好的rails dev)在TDD/BDD上做得最好,我遇到了水豚问题.

我有一个仅仅测试root_path工作的集成规范(Backbone历史记录启动,显示初始信息等等).

require 'spec_helper'

describe "RentalProperties", js: true do
  describe "GET /" do
    it "should show a list of properties" do
      visit root_path
      eventually{page.should have_content("Something")}
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我正在使用jasmine,sinon和capybara/rspec/webkit运行测试.我正在松散地遵循thinkbot上的"Rspec on Rails"一书(顺便说一句很棒的书),以及本教程:http://tinnedfruit.com/2011/03/03/testing-backbone-apps-with-jasmine- sinon.html.

运行上述规范时,我遇到了这个错误:

undefined|0|ReferenceError: Strict mode forbids implicit creation of global property 'csrf_token'
Run Code Online (Sandbox Code Playgroud)

我花了很长时间对其进行排序,因为这个错误确实没有google-able.

最终我在JS中使用"use strict-mode"偶然发现了.本质上,这将使用一些新的EMCA5脚本约定.它将捕获更多编码bloopers,并使您无法访问全局变量.所有美好的事物.

所以我检查一下,在我的sinon.js文件中,我看到:

"use strict";
Run Code Online (Sandbox Code Playgroud)

在文件的第36行.瞧,我注意到这条线,我的测试工作得很好.

这是我的问题:为什么使用严格搞乱csrf?我假设这与我的rails布局中的csrf_meta_tags有关.如果可能的话,我想把这条线放回到sinon js中,因为我认为它是"正确的事情"

有没有人有这方面的更多信息?我提前感谢任何细节!

javascript ruby-on-rails backbone.js jasmine sinon

12
推荐指数
1
解决办法
1万
查看次数

Jest Mock功能和Sinon间谍有什么区别

我正在用Jest嘲笑一个函数,文档说他们真的是'间谍'.我也看过在SinonJS中使用间谍,但我发现两者之间没有明显区别.如果他们服务于同一目的,有没有理由选择一个而不是另一个?

Jest Mock功能

SinonJS

javascript sinon jestjs

12
推荐指数
1
解决办法
4951
查看次数

如何使用Sinon/Qunit模拟"超时"或"失败"响应?

我没有解决模拟成功条件的问题,但似乎无法理解如何在使用Sinon和Qunit测试和ajax函数时模拟失败/超时条件:

我的设置如下:

$(document).ready( function() {

    module( "myTests", {
        setup: function() {
            xhr = sinon.sandbox.useFakeXMLHttpRequest();
            xhr.requests = [];
            xhr.onCreate = function (request) {
                xhr.requests.push(request);
            };

            myObj = new MyObj("#elemSelector");
        },
        teardown: function() {
            myObj.destroy();
            xhr.restore();
        }
    });
Run Code Online (Sandbox Code Playgroud)

和我的成功案例测试,愉快地运行并接收/通过接收的数据到成功方法是这样的:

    test( "The data fetch method reacts correctly to receiving data", function () {
        sinon.spy(MyObject.prototype, "ajaxSuccess");

        MyObject.prototype.fetchData();

        //check a call got heard
        equal(1, xhr.requests.length);

        //return a success method for that obj
        xhr.requests[0].respond(200, { "Content-Type": "application/json" },
                '[{ "responseData": "some test data" }]');

        //check the …
Run Code Online (Sandbox Code Playgroud)

javascript jquery unit-testing qunit sinon

11
推荐指数
1
解决办法
5835
查看次数

使用Sinon来存根链接的Mongoose调用

我得到了如何对Mongoose模型进行存根(感谢用Sinon一个Mongoose模型进行Stubbing),但是我不太明白如何将调用存根如下:

myModel.findOne({"id": someId})
    .where("someBooleanProperty").equals(true)
    ...
    .exec(someCallback);
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法:

var findOneStub = sinon.stub(mongoose.Model, "findOne");
sinon.stub(findOneStub, "exec").yields(someFakeParameter);
Run Code Online (Sandbox Code Playgroud)

没有用,有什么建议吗?

mongoose node.js sinon

11
推荐指数
2
解决办法
6712
查看次数

Node Express测试模拟res.status(状态).json(obj)

尝试测试我的方法时出现以下错误:

TypeError:无法调用未定义的方法'json'

下面是我的代码,如果我从测试方法中删除res.status,我会得到"status"的相同错误.

我如何定义'json'所以我没有得到一个异常抛出:

res.status(404)上传.json(误差);

在测试此功能时.

stores.js

{ //the get function declared above (removed to ease of reading)
        // using a queryBuilder
        var query = Stores.find();
        query.sort('storeName');
        query.exec(function (err, results) {
            if (err)
                res.send(err);
            if (_.isEmpty(results)) {
                var error = {
                    message: "No Results",
                    errorKey: "XXX"
                }
                res.status(404).json(error);
                return;
            }
            return res.json(results);
        });
    }
Run Code Online (Sandbox Code Playgroud)

storesTest.js

it('should on get call of stores, return a error', function () {

    var mockFind = {
        sort: function(sortOrder) {
            return this;
        },
        exec: function (callback) …
Run Code Online (Sandbox Code Playgroud)

mocha.js node.js express sinon

11
推荐指数
1
解决办法
7547
查看次数

与sinon和bluebird一起确定一个有希望的功能

在我想测试的文件中,我有以下代码:

var httpGet = Promise.promisify(require("request").get);
httpGet(endpoint, {
    auth: {bearer: req.body.access_token},
    json: true
})
    .then(...)
Run Code Online (Sandbox Code Playgroud)

现在,在我的测试中,我想确保httpGet被调用一次,并确保参数有效.在被宣传之前,我的测试看起来像这样:

beforeEach(function () {
    request.get = sinon.stub()
        .yields(null, null, {error: "test error", error_description: "fake google error."});
});

afterEach(function () {
    expect(request.get).to.have.been.calledOnce();
    var requestArgs = request.get.args[0];
    var uri = requestArgs[0];

    expect(uri).to.equal(endpoint);
    //...
});
Run Code Online (Sandbox Code Playgroud)

不幸的是,当request.get被宣传时,这不再有效.我尝试了stubing request.getAsync(因为bluebird将"Async"附加到promisified函数),但这也不起作用.有任何想法吗?

javascript node.js promise sinon bluebird

11
推荐指数
1
解决办法
3964
查看次数

使用Enzyme测试React组件中<iframe>的内容

我写了一个简单的React组件,它呈现了一个<iframe>:

export class Iframe extends React.component {
   render() {
        return <iframe src={ this.props.src } />;
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图通过检查加载的内容src是否正确填充来测试它<iframe>.为了做到这一点,我尝试访问frame.contentWindow,但在用Enzyme安装后它总是返回undefined.

我试图<iframe>用Sinon 模拟内容FakeXMLHttpRequest:

server = sinon.fakeServer.create();
server.respondWith('GET', 'test', [200, { 'Content-Type': 'text/html' }, '<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><body><div class="myClass">Amazing Unicorn</div></body></html>']);
container = mount(<Iframe src='test' />);
Run Code Online (Sandbox Code Playgroud)

并与<iframe src='data:text/html' >:

const src = 'data:text/html;charset=utf-8,<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><body><div class="myClass">Amazing Unicorn</div></body></html>';
container = mount(<Iframe src={ src } />);
Run Code Online (Sandbox Code Playgroud)

但在两种情况下用酶测试:

container = mount(<Iframe src='...' />); …
Run Code Online (Sandbox Code Playgroud)

javascript iframe sinon reactjs enzyme

11
推荐指数
1
解决办法
2486
查看次数

Sinon.JS - 如何从存根中获取参数?

我正在尝试使用Sinon来测试看起来有点像这样的JS组件......

import Bootbox from "../helpers/bootbox";
import Guard from "../helpers/guard";
import UrlHelper from "../helpers/url-helper";

export default class DeleteButton {

    /**
     * Creates an instance of DeleteButton.
     * 
     * @param {object} element The DOM element to make into a delete button.
     * 
     * @memberOf DeleteButton
     */
    constructor(element) {
        Guard.throwIf(element, "element");

        this.deleteUri = element.getAttribute("data-delete-uri") || UrlHelper.current.url().split('?')[0];        
        this.title = element.getAttribute("data-title") || `Delete the item?`;
        this.cancelText = element.getAttribute("data-cancel") || `Cancel`;
        this.confirmText = element.getAttribute("data-confirm") || `Remove`;
        this.message = element.getAttribute("data-message") || `Do you want to delete the …
Run Code Online (Sandbox Code Playgroud)

javascript sinon sinon-chai

11
推荐指数
1
解决办法
9789
查看次数

Sinon存根调用Forfake参数

之前我有完整的以下存根

sinon.stub(console, 'log', () => {
    // Check what the arguments holds 
    // And either console.info it or do nothing
});
Run Code Online (Sandbox Code Playgroud)

例如,console.info(arguments)在里面添加,会告诉我任何事情console.log.

随着版本2xxI切换到callsFake:

sinon.stub(console, 'log').callsFake(() => {
    // Check what the arguments holds
    // And either console.info it or do nothing
});
Run Code Online (Sandbox Code Playgroud)

这现在更长的工作.console.info(arguments)有市集价值,与console.log传递无关.

我究竟做错了什么?!

javascript sinon

11
推荐指数
1
解决办法
7278
查看次数

用Sinon测试axios调用,使用redux和Karma

你好在redux文档中进行测试,他们有这个例子来测试api调用:

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as actions from '../../actions/counter'
import * as types from '../../constants/ActionTypes'
import nock from 'nock'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
  })

  it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', (done) => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { body: { todos: ['do something'] }})

    const expectedActions = [
      { type: types.FETCH_TODOS_REQUEST },
      { type: types.FETCH_TODOS_SUCCESS, body: { todos: …
Run Code Online (Sandbox Code Playgroud)

node.js sinon karma-runner nock redux

10
推荐指数
2
解决办法
2811
查看次数