[英]Force-failing a Jasmine test
If I have code in a test that should never be reached (for example the fail
clause of a promise sequence), how can I force-fail the test? 如果我在永远不会达到的测试中有代码(例如,promise序列的
fail
子句),我怎么能强制失败测试?
I use something like expect(true).toBe(false);
我使用
expect(true).toBe(false);
but this is not pretty. 但这并不漂亮。
The alternative is waiting for the test to timeout, which I want to avoid (because it is slow). 另一种方法是等待测试超时,我想避免(因为它很慢)。
Jasmine provides a global method fail()
, which can be used inside spec blocks it()
and also allows to use custom error message: Jasmine提供了一个全局方法
fail()
,它可以在spec it()
块内部使用it()
并允许使用自定义错误消息:
it('should finish successfully', function (done) {
MyService.getNumber()
.success(function (number) {
expect(number).toBe(2);
done();
})
.fail(function (err) {
fail('Unwanted code branch');
});
});
This is built-in Jasmine functionality and it works fine everywhere in comparison with the 'error' method I've mentioned below. 这是内置的Jasmine功能,与我在下面提到的“错误”方法相比,它在任何地方都可以正常工作。
Before update: 更新前:
You can throw an error from that code branch, it will fail a spec immediately and you'll be able to provide custom error message: 您可以从该代码分支引发错误,它将立即失败规范,您将能够提供自定义错误消息:
it('should finish successfully', function (done) {
MyService.getNumber()
.success(function (number) {
expect(number).toBe(2);
done();
})
.fail(function (err) {
throw new Error('Unwanted code branch');
});
});
But you should be careful, if you want to throw an error from Promise success handler then()
, because the error will be swallowed in there and will never come up. 但是你应该小心,如果你想从Promise成功处理程序
then()
抛出一个错误,因为错误将被吞并在那里,永远不会出现。 Also you should be aware of the possible error handlers in your app, which might catch this error inside your app, so as a result it won't be able to fail a test. 此外,您应该知道应用程序中可能存在的错误处理程序,这可能会在您的应用程序中捕获此错误,因此无法通过测试失败。
Thanks TrueWill for bringing my attention to this solution. 感谢TrueWill将我的注意力集中在这个解决方案上。 If you are testing functions that return promises, then you should use the
done
in the it()
. 如果您正在测试返回promises的函数,那么您应该使用
it()
的done
。 And instead of calling fail()
you should call done.fail()
. 而不是调用
fail()
你应该调用done.fail()
。 See Jasmine documentation . 请参阅Jasmine文档 。
Here is an example 这是一个例子
describe('initialize', () => {
// Initialize my component using a MOCK axios
let axios = jasmine.createSpyObj<any>('axios', ['get', 'post', 'put', 'delete']);
let mycomponent = new MyComponent(axios);
it('should load the data', done => {
axios.get.and.returnValues(Promise.resolve({ data: dummyList }));
mycomponent.initialize().then(() => {
expect(mycomponent.dataList.length).toEqual(4);
done();
}, done.fail); // <=== NOTICE
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.