gpt4 book ai didi

javascript - Jest 模拟未覆盖函数或返回错误

转载 作者:行者123 更新时间:2023-12-02 22:32:44 25 4
gpt4 key购买 nike

我正在尝试为 csvtojson 编写一个 Jest 模拟测试,但出现错误:

TypeError: Cannot read property 'subscribe' of undefined

api.js:

import csv = require('csvtojson')
const request = require('request')

export const getApiData = url => {
return csv()
.fromStream(request.get(url)
.subscribe(json => json)
}

api.test.js

import { getApiData } from '../api';
const csv = require('csvtojson');

jest.mock('csvtojson', () => {
const fromStream = jest.fn();
const subscribe = jest.fn(() => new Promise(resolve => setTimeout(resolve, 0)));
const result = { fromStream, subscribe };
return jest.fn(() => result);
});
jest.mock('request', () => {
return { get: jest.fn() };
});
describe('getApiData', () => {
beforeEach(() => {
getApiData('http://test.com');
});
describe('csv', () => {
expect(csv).toHaveBeenCalled();
});
});

然后我测试了它,如果我从 getApiData 函数中删除 fromStream 它可以工作,但后来我的报道显示 json => json尚未被调用。

我真的很困惑。有人可以帮忙吗?

最佳答案

这是单元测试解决方案:

api.js:

const csv = require('csvtojson');
const request = require('request');

export const getApiData = url => {
return csv()
.fromStream(request.get(url))
.subscribe(json => json);
};

api.test.js:

import { getApiData } from './api';
const csv = require('csvtojson');
const request = require('request');

jest.mock('csvtojson', () => {
const mCsvtojson = {
fromStream: jest.fn().mockReturnThis(),
subscribe: jest.fn()
};
return jest.fn(() => mCsvtojson);
});
jest.mock('request', () => {
return { get: jest.fn() };
});

describe('getApiData', () => {
it('csv', done => {
const mResponse = { name: 'UT' };
let observer;
csv()
.fromStream()
.subscribe.mockImplementationOnce(onSuccess => {
observer = onSuccess;
});
request.get.mockResolvedValueOnce(mResponse);
getApiData('http://test.com');
const mJSON = {};
expect(observer(mJSON)).toEqual({});
expect(request.get).toBeCalledWith('http://test.com');
expect(csv).toHaveBeenCalled();
expect(csv().fromStream).toBeCalledWith(expect.any(Object));
done();
});
});

100%覆盖率的单元测试结果:

PASS  src/stackoverflow/58842143/api.test.js (10.249s)
getApiData
✓ csv (8ms)

----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
api.js | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.139s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58842143

关于javascript - Jest 模拟未覆盖函数或返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58842143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com