Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取模拟响应没有JSON方法_Javascript_Webpack_Fetch_Karma Runner_Isparta - Fatal编程技术网

Javascript 获取模拟响应没有JSON方法

Javascript 获取模拟响应没有JSON方法,javascript,webpack,fetch,karma-runner,isparta,Javascript,Webpack,Fetch,Karma Runner,Isparta,我正试图让fetch mock在我的测试设置中工作,但是响应对象看起来与预期的不同 具体来说,它没有json方法 下面是我正在调用的类,实际调用的是fetch: import 'whatwg-fetch'; export class Store { load() { return fetch("/api", { method: "get", headers: {'Content-Type': 'application/json'} }); }

我正试图让fetch mock在我的测试设置中工作,但是响应对象看起来与预期的不同

具体来说,它没有
json
方法

下面是我正在调用的类,实际调用的是fetch:

import 'whatwg-fetch';
export class Store {

  load() {

    return fetch("/api", {
      method: "get",
      headers: {'Content-Type': 'application/json'}
    });
  }

}
以下是测试代码的一个片段:

import fetchMock from 'fetch-mock';
fetchMock.get("*", {code: "1", name: "cde", image: 'hello.jpeg'})
      this.store = new Store;
      this.store.load().then(response => console.log(response._bodyInit()));
      console.log('hello', this.brandStore.brands[0]);
      fetchMock.restore();
控制台将打印:

Response{
type: 'default',
status: 200,
ok: true,
statusText: 'OK',
headers: Headers{map: Object{content-type: ...}},
url: '/api',
_bodyInit: '{"code":"1","name":"cde","image":"hello.jpeg"}',
_bodyText: '{"code":"1","name":"cde","image":"hello.jpeg"}'
}
此错误也会得到输出:

'Unhandled promise rejection', TypeError{line: 4005, sourceURL: 'http://localhost:9876/base/test/stores/BrandStore.spec.js?572679e0c28b63839a5f5829ef1a60b8d62f8b84', stack: 'http://localhost:9876/base/test/stores/BrandStore.spec.js?572679e0c28b63839a5f5829ef1a60b8d62f8b84:4005:168
run@http://localhost:9876/base/node_modules/babel-polyfill/dist/polyfill.js?00cf5c53ec5ebd52d0521aed551c593eef05a0d6:3911:29
http://localhost:9876/base/node_modules/babel-polyfill/dist/polyfill.js?00cf5c53ec5ebd52d0521aed551c593eef05a0d6:3924:31
flush@http://localhost:9876/base/node_modules/babel-polyfill/dist/polyfill.js?00cf5c53ec5ebd52d0521aed551c593eef05a0d6:1209:11'}
我的因果报应(带有网页包配置)看起来像:

const webpack = require('webpack');
var argv = require('yargs').argv;
var path = require('path');
let srcPath = path.join(__dirname, '/../src/');

const webpackConfig = {
    devtool: 'inline-source-map',
    resolve: {
        // allow us to import components in tests like:
        // import Example from 'components/Example';
        root: path.resolve(__dirname, './src'),

        // allow us to avoid including extension name
        extensions: ['', '.js', '.jsx', '.css', '.scss', '.json'],

        // required for enzyme to work properly
        alias: {
            'sinon': 'sinon/pkg/sinon',
        }
    },
    module: {
        // don't run babel-loader through the sinon module
        noParse: [
            /node_modules\/sinon\//
        ],
        isparta: {
                embedSource: true,
                noAutoWrap: true,
                // these babel options will be passed only to isparta and not to babel-loader
                babel: {
                        presets: ['es2015', 'stage-0', 'react']
                }
        },
        // run babel loader for our tests
        loaders: [
            {
        test: /\.(js|jsx)$/,
        loader: 'babel',
        exclude: path.resolve(__dirname, 'node_modules'),
        query: {
            plugins: ['transform-decorators-legacy'],
          presets: ['es2015', 'airbnb', 'stage-1', 'react']
        }
      },
            {
                test: /\.json$/, loader: 'json'
            },
            {
                test: /\.scss$/,
                exclude: /[\/\\](node_modules|bower_components|public)[\/\\]/,
                loaders: [
                    'style?sourceMap',
                    'css?modules&importLoaders=1&localIdentName=[local]',
                    'postcss',
                    'sass'
                ]
            },
            {
                test: /\.css$/,
                exclude: /[\/\\](node_modules|bower_components|public)[\/\\]/,
                loaders: [
                    'style?sourceMap',
                    'css?modules&importLoaders=1&localIdentName=[local]'
                ]
            }
        ],
        preLoaders: [ { //delays coverage til after tests are run, fixing transpiled source coverage error
            test: /\.(jsx|js)$/,
            include: path.resolve('src/'),
            loader: 'isparta',
        } ]
    },
    plugins: [
        new webpack.IgnorePlugin(/node-fetch/)
    ],
    // required for enzyme to work properly
    externals: {
        'jsdom': 'window',
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': 'window',
        'react/addons': true
    },
};

module.exports = function(config) {
    config.set({
        browsers: ['PhantomJS'],
        singleRun: !argv.watch,
        frameworks: ['mocha', 'chai'],
        reporters: ['spec', 'coverage'],

        // include some polyfills for babel and phantomjs
        files: [
            'node_modules/whatwg-fetch/fetch.js',
            'node_modules/babel-polyfill/dist/polyfill.js',
            './node_modules/phantomjs-polyfill/bind-polyfill.js',
            'test/**/*.js'
        ],
        preprocessors: {
      // add webpack as preprocessor
      'src/**/*.js': ['webpack', 'sourcemap'],
      'test/**/*.js': ['webpack', 'sourcemap']
    },
        // A lot of people will reuse the same webpack config that they use
        // in development for karma but remove any production plugins like UglifyJS etc.
        // I chose to just re-write the config so readers can see what it needs to have
        webpack: webpackConfig,
        webpackMiddleware: {
            noInfo: true
        },
        coverageReporter: {
            dir: 'coverage/',
            reporters: [
                { type: 'html' },
                { type: 'text' }
            ]
        },
        // tell karma all the plugins we're going to be using to prevent warnings
        plugins: [
            'karma-mocha',
            'karma-chai',
            'karma-webpack',
            'karma-phantomjs-launcher',
            'karma-spec-reporter',
            'karma-sourcemap-loader',
            'karma-coverage'
        ]
    });
};