如何使用 jest 测试如下所示的函数?
lightboxUrl: function () {
var componentId = this.options.componentId
if (componentId) {
var album = this.model.get('album')
var shortcut = this.model.get('shortcut')
return '/lightbox/' + componentId + '/' + album + '/' + shortcut
}
}
JavaScript 测试新手。非常感谢任何帮助。如果您还需要任何其他信息,请告诉我。
最佳答案
我只是假设并删除了一些未提供的细节。
这是灯箱项目
export default function lightboxParent(componentId) {
return {
options: {
componentId,
},
model: {
get: id => (id === "album" ? "album" : "shortcut"),
},
lightboxUrl: function() {
var componentId = this.options.componentId;
if (componentId) {
var album = this.model.get("album");
var shortcut = this.model.get("shortcut");
return "/lightbox/" + componentId + "/" + album + "/" + shortcut;
}
}
}
}
这是 Jest 测试
describe("lightbox url", () => {
it("should be valid url", () => {
expect(lightboxParent(1).lightboxUrl()).toBe(
"/lightbox/1/album/shortcut"
);
});
it("should not resolve valid url, no componentId", () => {
expect(lightboxParent().lightboxUrl()).toBe(undefined);
});
});
我为此使用了codesandbox,https://codesandbox.io/s/n4mlqkr4qj
这是一个基本测试,只是检查 lightboxUrl
方法返回的 url,或者如果没有 componentId,则它是 未定义
,因为我提供了整个 src我只是保留了一些基本的假设
关于javascript - 用 jest 测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52137054/