所以我有一个名为article.js的文件,它看起来像这样:
import a from 'indefinite';
function formatArticle(value) {
return a(value);
}
export { formatArticle };
export default formatArticle;还有一个名为index.js的文件,如下所示:
import formatArticle from './article';
const format = (value, incomingFormat) => {
if (incomingFormat === 'indefinite') {
return formatArticle(value);
}
return value;
};
export default format;我正在尝试测试我正在导入的formatArticle函数是否在应该被调用的时候被调用。为此,我使用了sinon和chai。下面是测试文件:
import chai, { expect } from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import format from './index';
import * as article from './article';
chai.use(sinonChai);
describe('format', () => {
describe('article', () => {
describe(`when incoming format is 'indefinite'`, () => {
const value = 'some value';
const indefinite = 'indefinite';
let formatArticleSpy;
beforeEach(() => {
formatArticleSpy = sinon.spy(article, 'formatArticle');
format(value, indefinite);
});
it('should call formatArticle', () => {
expect(formatArticleSpy).to.have.been.calledWith(value);
});
});
});
});但是,每当我运行测试套件时,它都会告诉我:
AssertionError: expected formatArticle to have been called with arguments some value
在这个设置中,我做错了什么?使用间谍是试图做到这一点的正确方式吗?我也尝试过使用sinon.stub,也得到了同样的结果。
感谢任何人的帮助!
发布于 2020-04-09 10:34:10
sinon.js使用Link Seams来存根独立的函数。用于您的案例的formatArticle函数。
例如。
article.js
import a from './indefinite';
function formatArticle(value) {
return a(value);
}
export default formatArticle;indefinite.js
export default function a(value) {
return 'real data';
}index.js
import formatArticle from './article';
const format = (value, incomingFormat) => {
if (incomingFormat === 'indefinite') {
return formatArticle(value);
}
return value;
};
export default format;index.test.js
import proxyquire from 'proxyquire';
import sinon from 'sinon';
describe('61104001', () => {
it('should pass', () => {
const value = 'some value';
const indefinite = 'indefinite';
const formatArticleStub = sinon.stub().returns('fake data');
const format = proxyquire('./', {
'./article': { default: formatArticleStub },
}).default;
const actual = format(value, indefinite);
sinon.assert.match(actual, 'fake data');
sinon.assert.calledWithExactly(formatArticleStub, value);
});
// you can do the rest
});单元测试结果和覆盖率报告:
61104001
✓ should pass (2259ms)
1 passing (2s)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 72.73 | 50 | 33.33 | 72.73 |
article.ts | 66.67 | 100 | 0 | 66.67 | 4
indefinite.ts | 50 | 100 | 0 | 50 | 2
index.ts | 83.33 | 50 | 100 | 83.33 | 8
---------------|---------|----------|---------|---------|-------------------源代码:https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/61104001
https://stackoverflow.com/questions/61104001
复制相似问题