我正在尝试为没有return语句的函数编写测试用例。 你能告诉我怎么做吗?我写过测试用例,但我不确定它是否正确
/**
* Load sports.js script. That script will execute an analytics sportsView immediately.
* @returns {undefined}
*/
export function loadsports() {
if (typeof sports === 'undefined') {
let sportsElement = document.createElement('script');
sportsElement.src = '~^sports, sports.js~^';
sportsElement.async = true; // the script will be executed asynchronously as soon as it is available
let firstSportsElement = document.getElementsByTagName('script')[0];
firstSportsElement.parentNode.insertBefore(sportsElement, firstSportsElement);
}
}
/**
* Record a sports view in analytics using the data available in aports.ent.sportsData object
* @returns {undefined}
*/
export function sportsView() {
let sportsData = getSportsData();
if (isSportsAvailable() && sportsData) {
sports.view(sportsData);
}
}
/* test case */
describe('loadsports test cases', function() {
it('loadsports method', function() {
console.log("loadsports method");
// sportsAnalytic.sportsView();
expect(true).to.be.true;
});
});
答案 0 :(得分:1)
您的loadSports
功能会添加script
标记。要验证该行为:
describe('when sports is not loaded', function () {
it('adds a script element', function () {
loadSports()
let sportsElement = document.querySelector(/* target the script tag that should have been appended */)
expect(sportsElement).to.exist
})
})
您的sportsView
函数会产生很多影响:阅读getSportsData()
,检查是否isSportsAvailable()
,然后调用sports.view
。如果明确地使用它的依赖关系会更好,所以你可以在测试期间注入它们:
// revised
export function sportsView(getSportsData, isSportsAvailable, sports) {
let sportsData = getSportsData()
if (isSportsAvailable() && sportsData) {
sports.view(sportsData)
}
}
现在,您可以将伪实现作为参数传递给sportsView
来控制其行为。
import { expect } from 'chai'
import sportsView from 'path/to/sportsView'
describe('sportsView', function () {
describe('when sports and sportsData is available', function () {
it('adds the data to the sports view', function (done) {
let someData = {/* some data */}
let isSportsAvailable = function () { return true }
let getSportsData = function () { return someData }
let sports = {
view: function(data) {
expect(data).to.equal(someData)
done()
}
}
sportsView(getSportsData, isSportsAvailable, sports)
})
})
describe('when sports is not available...', function () {}) // etc
})
拥有大量全局状态会使测试代码变得非常困难或不可能。查看dependency injection作为模式以包含和控制代码的效果。
祝你好运!