gpt4 book ai didi

javascript - Jasmine Angular 测试指令应该失败

转载 作者:太空狗 更新时间:2023-10-29 18:15:11 25 4
gpt4 key购买 nike

所以我做了一个简单的指令,当输入无效时抛出错误,但当我尝试抛出时它成功了,这是正确的,但是当我 not.toThrow()它同样成功。这告诉我我做错了什么,但无法弄清楚是什么。有人可以帮忙吗?

测试

// Test component
@Component({
template: `<div [addClass]="data"></div> `
})
class TestAddClassComponent {
data: string | Array<string>;
}


describe('AddClassDirective', () => {
let component: TestAddClassComponent;
let fixture: ComponentFixture<TestAddClassComponent>;
let element: DebugElement;

beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestAddClassComponent, AddClassDirective]
});
fixture = TestBed.createComponent(TestAddClassComponent);
component = fixture.componentInstance;
element = fixture.debugElement.query(By.css('div'));
});

it('should throw error', () => {
component.data = 'some-invalid-input';
fixture.detectChanges();

expect(component).toThrow();
// Same result as:
// expect(component).not.toThrow();

});
});

指令

@Directive({
selector: '[addClass]'
})
export class AddClassDirective implements OnInit {

ngOnInit() {
if (this.valid(this.value)) {
// Do something
} else {
throw new Error();
}
}
}

最佳答案

toThrow 需要一个函数作为参数。

将你的断言改成这样

expect(
() => fixture.detectChanges()
.toThrow()

关于javascript - Jasmine Angular 测试指令应该失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49937553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com