强制使 Jasmine 测试失败
Force-failing a Jasmine test
如果我在测试中有永远不会到达的代码(例如承诺序列的 fail
子句),我如何强制测试失败?
我使用类似 expect(true).toBe(false);
的东西,但这并不漂亮。
另一种方法是等待测试超时,我想避免这种情况(因为它很慢)。
Jasmine 提供了一个全局方法 fail()
,可以在 spec 块中使用 it()
并且还允许使用自定义错误消息:
it('should finish successfully', function (done) {
MyService.getNumber()
.success(function (number) {
expect(number).toBe(2);
done();
})
.fail(function (err) {
fail('Unwanted code branch');
});
});
这是内置的 Jasmine 功能,与我在下面提到的 'error' 方法相比,它在任何地方都能正常工作。
更新前:
您可以从该代码分支抛出错误,它会立即使规范失败,您将能够提供自定义错误消息:
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');
});
});
但是你应该小心,如果你想从 Promise 成功处理程序 then()
中抛出错误,因为错误将被吞噬在那里,永远不会出现。此外,您还应该了解您的应用程序中可能存在的错误处理程序,它们可能会在您的应用程序内部捕获此错误,因此它无法通过测试。
感谢 TrueWill 让我注意到这个解决方案。如果您正在测试 return 承诺的功能,那么您应该在 it()
中使用 done
。而不是调用 fail()
你应该调用 done.fail()
。参见 Jasmine documentation。
这是一个例子
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
});
});
如果我在测试中有永远不会到达的代码(例如承诺序列的 fail
子句),我如何强制测试失败?
我使用类似 expect(true).toBe(false);
的东西,但这并不漂亮。
另一种方法是等待测试超时,我想避免这种情况(因为它很慢)。
Jasmine 提供了一个全局方法 fail()
,可以在 spec 块中使用 it()
并且还允许使用自定义错误消息:
it('should finish successfully', function (done) {
MyService.getNumber()
.success(function (number) {
expect(number).toBe(2);
done();
})
.fail(function (err) {
fail('Unwanted code branch');
});
});
这是内置的 Jasmine 功能,与我在下面提到的 'error' 方法相比,它在任何地方都能正常工作。
更新前:
您可以从该代码分支抛出错误,它会立即使规范失败,您将能够提供自定义错误消息:
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');
});
});
但是你应该小心,如果你想从 Promise 成功处理程序 then()
中抛出错误,因为错误将被吞噬在那里,永远不会出现。此外,您还应该了解您的应用程序中可能存在的错误处理程序,它们可能会在您的应用程序内部捕获此错误,因此它无法通过测试。
感谢 TrueWill 让我注意到这个解决方案。如果您正在测试 return 承诺的功能,那么您应该在 it()
中使用 done
。而不是调用 fail()
你应该调用 done.fail()
。参见 Jasmine documentation。
这是一个例子
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
});
});